package com.bbcare.followup.plat.service.impl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.store.ibatis.IEltDstRecoreDAO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.followup.plat.entity.BsEvaluationStandard;
import com.bbcare.followup.plat.entity.FuAssessMentPosition;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PtEvaluationGuide;
import com.bbcare.followup.plat.service.IFollowEvaluationScoreService;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.store.ibatis.IFollowEvaluationDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientqueryCardDAO;
import com.bbcare.plat.support.service.IBizInterAsClient;

/**
 *
 * @name: FollowEvaluationService.java
 * @author: tao
 * @createTime: 2017年6月20日
 * @description: 随访评测得分 相关sevice服务实现类 基本业务逻辑代码复制1.0 暂无改动
 * @modify:
 *
 */
@Service
public class FollowEvaluationScoreService implements IFollowEvaluationScoreService {
	private final Log logger = LogFactory.getLog(FollowEvaluationScoreService.class);

	@Resource(name = "jedisPool")
	private JedisPool jedisPool;

	@Autowired
	IFollowEvaluationDAO followEvaluationDao;

	@Autowired
	private IBizInterAsClient bizInterClient;

    @Autowired
    private IFollowEvaluationService followEvaluationService;

    @Autowired
	private IPatientqueryCardDAO patientqueryCardDAO;

    @Autowired
	private IEltDstRecoreDAO iEltDstRecoreDAO;

	@Autowired
	IPatientDAO patientdao;


	@Override
	public Map<String, Object> getNeuropsychologyScore(ArrayList<Object> postionIds, Date date) throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);
			int day = DateUtil.daysBetween(date, new Date());
			float bigMovement = 0, fineAction = 0, adaptability = 0, language = 0, socialBehavior = 0;
			for (Object id : postionIds) {
				Map<String, Object> map = ToolUtils.stringToMap(jedis.hmget("Postion", "Neuropsychology_" + id).get(0));
				float score = 0;
				int month = Integer.parseInt((String) map.get("monthForAge"));
				if (month >= 1 && month <= 12)
					score = 1;
				if (month > 12 && month <= 36)
					score = 3;
				if (month > 36 && month <= 84)
					score = 6;
				String project = (String) map.get("project");
				if (project.equals("大运动"))
					project = "大 运 动";
				if (project.equals("语言"))
					project = "语    言";
				String str = jedis.hmget("ExaminationPaper","Neuropsychology_" + map.get("monthForAge") + "_"+ project).get(0);
				List<String> list = JSON.parseArray(str, String.class);
				if (project.equals("大 运 动"))
					bigMovement += score / list.size();
				if (project.equals("精细动作"))
					fineAction += score / list.size();
				if (project.equals("适应能力"))
					adaptability += score / list.size();
				if (project.equals("语    言"))
					language += score / list.size();
				if (project.equals("社交行为"))
					socialBehavior += score / list.size();
			}

			float score = 0;
			java.text.DecimalFormat df = new java.text.DecimalFormat("#.#");
			float time = (int) (day / 30)+ Float.parseFloat(df.format(((float) (day % 30)) / 30));

			score = Float.parseFloat(df.format((bigMovement + fineAction+ adaptability + language + socialBehavior)* 100 / 5 / time));
			bigMovement = Float.parseFloat(df.format(bigMovement * 100 / time));
			fineAction = Float.parseFloat(df.format(fineAction * 100 / time));
			adaptability = Float.parseFloat(df.format(adaptability * 100 / time));
			language = Float.parseFloat(df.format(language * 100 / time));
			socialBehavior = Float.parseFloat(df.format(socialBehavior * 100/ time));

			Map<String, Object> scoreMap = new HashMap<String, Object>();
			scoreMap.put("总分", score);
			scoreMap.put("大 运 动", bigMovement);
			scoreMap.put("精细动作", fineAction);
			scoreMap.put("适应能力", adaptability);
			scoreMap.put("语    言", language);
			scoreMap.put("社交行为", socialBehavior);

			return scoreMap;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

    //获得DST指导
	public Map getNeuropsychologyGuide(Map<String, Object> scoreMap,Date birthday)  throws Exception{
		int day = DateUtil.daysBetween(birthday, new Date());
		Integer monthAge = (day / 30)+(day%30>14?1:0);
		Map map = new HashMap();
		for (String key :scoreMap.keySet()) {

			String name = getNeuropsychologyToDst(key,monthAge);
			String result = iEltDstRecoreDAO.getDstGuide(monthAge,name,getNeuropsychologyTestResult(key,(float)scoreMap.get(key)));
			if(result!=null){
				map.put(name,result);
			}

		}

		return map;
	}

	public Integer getNeuropsychologyTestResult(String name ,float value){
		if(name.equals("bigMovement")&& value< 85)	{
			return 0;
		}
		if(name.equals("fineAction")&& value< 85)	{
			return 0;
		}
		if(name.equals("language")&& value< 85)	{
			return 0;
		}
		if(name.equals("socialBehavior")&& value< 85)	{
			return 0;
		}
		if(name.equals("score")&& value< 69.9)	{
			return 0;
		}

		return 0;
	}

	public String getNeuropsychologyToDst(String NeurName ,Integer monthAge){
		if (monthAge < 24) {
			if(NeurName.equals("精细动作"))
			   return "运动";
		} else {
			if(NeurName.equals("大 运 动"))
				return "运动";
		}
		if(NeurName.equals("适应能力")){
			return "认知";
		}
		if(NeurName.equals("语    言")){
			return "语言";
		}
		if(NeurName.equals("社交行为")){
			return "生活与交往";
		}
		if(NeurName.equals("总分")){
			return "训练玩具";
		}
		return "";
	}
	@Override
	public Map<String, Object> getBaileyScreeningScore(
			ArrayList<Object> postionIds, Date date) throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);
			int day = DateUtil.daysBetween(date, new Date());
			// 已经存在的项目
			List<String> isRepeat = new ArrayList<String>();
			// 答题项在项目最开始的值
			Map<String, Integer> indexId = new HashMap<>();

			float cognitive = 0, understand = 0, express = 0, fineMotor = 0, bigAction = 0;
			for (Object id : postionIds) {
				Map<String, Object> map = ToolUtils.stringToMap(jedis.hmget("Postion", "BaileyScreening_" + id).get(0));
				String keyString = map.get("monthForAge") + "_"+ map.get("project");
				if (!isRepeat.contains(keyString)) {
					isRepeat.add(keyString);
					indexId.put(keyString, Integer.parseInt(id.toString()));
				} else {
					int temp = indexId.get(keyString);
					if (temp > Integer.parseInt(id.toString()))
						indexId.put(keyString, Integer.parseInt(id.toString()));
				}
				if (map.get("project").equals("认知能力"))
					cognitive += 1;
				if (map.get("project").equals("语言理解"))
					understand += 1;
				if (map.get("project").equals("语言表达"))
					express += 1;
				if (map.get("project").equals("精细动作"))
					fineMotor += 1;
				if (map.get("project").equals("大动作"))
					bigAction += 1;
			}
			// 若起点不是第1项，起点之前的项目全部给分，即起点之前每项都得1分。
			for (Map.Entry<String, Integer> entry : indexId.entrySet()) {
				List<String> list = JSON.parseArray(
						jedis.hmget("ExaminationPaper","BaileyScreening_" + entry.getKey()).get(0),String.class);
				int index = list.indexOf(entry.getValue() + "");
				String[] keyStrings = entry.getKey().split("_");
				if (keyStrings[1].equals("认知能力"))
					cognitive += index;
				if (keyStrings[1].equals("语言理解"))
					understand += index;
				if (keyStrings[1].equals("语言表达"))
					express += index;
				if (keyStrings[1].equals("精细动作"))
					fineMotor += index;
				if (keyStrings[1].equals("大动作"))
					bigAction += index;
			}
			Map<String, Object> score = new HashMap<String, Object>();
			score.put("cognitive", cognitive);
			score.put("understand", understand);
			score.put("express", express);
			score.put("fineMotor", fineMotor);
			score.put("bigAction", bigAction);
			score.put("day", day);
			return score;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> getGesellScore(Map<String, Object> postionIds,
			Date date) throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			Map<String, Object> postions = new LinkedHashMap<String, Object>();
			// 题目中月份
			String[] times = { "0.93", "1.87", "2.8", "3.73", "4.67", "5.6","6.5", "7.5", "8.4", "9.3", "10.3", "11.2", "12.1", "13.1",
					"15", "18", "21", "24", "30", "36", "42", "48", "54", "60","72" };
			// 大运动
			Map<String, Object> sportsPostion = new LinkedHashMap<>();
			// 精细动作
			Map<String, Object> fineActionPostion = new LinkedHashMap<>();
			// 适应性
			Map<String, Object> adaptabilityPostion = new LinkedHashMap<>();
			// 语言
			Map<String, Object> languagePostion = new LinkedHashMap<>();
			// 个人——社会
			Map<String, Object> personalPostion = new LinkedHashMap<>();

			// 获取相当年龄
			String json3 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
					Constants.FOLLOW_EVALUATION_GESELL);
			if (StringUtils.isEmpty(json3)) {
				postions.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				postions.put("key", Constants.FOLLOW_EVALUATION_GESELL);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(postions);
				if (null != position) {
					json3 = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_GESELL, json3);
				}
			}
			String testTime = (String) postionIds.get("testTime");
			Date Testdate = null;
			if (StringUtils.isEmpty(testTime)) {
				Testdate = new Date();
			}else {
				Testdate = DateUtil.getDate_8(testTime);
			}

			//年龄保留一位小数
			DecimalFormat df = new DecimalFormat("#.0");
			//清除
			postions.clear();
			// 出生月份
			float CA = (float) (DateUtil.daysBetween(date,Testdate)) / 7;
			float CACopy = (float) (DateUtil.daysBetween(date,Testdate)) / 7;
			CA = Float.parseFloat(df.format(CA));
			JSONObject jsons =  JSONObject.parseObject(json3);

			//大运动
			float DA = calculate(times, jsons.getJSONObject("sportsPostion"),postionIds);
			if("NaN".equals(DA+"")) {
				DA = 0;
			}
			float DQ =(DA/CACopy)*100;
			DA = Float.parseFloat(df.format(DA));
			DQ = Float.parseFloat(df.format(DQ));
			sportsPostion.clear();
			sportsPostion.put("DA", DA);
			sportsPostion.put("CA", CA);
			sportsPostion.put("DQ", DQ);
			sportsPostion.put("level", this.matchlevel(DQ));
			postions.put("sportsPostion", sportsPostion);
			//精细动作
			DA = calculate(times,jsons.getJSONObject("fineActionPostion"),postionIds);
			if("NaN".equals(DA+"")) {
				DA = 0;
			}
			DQ =(DA/CACopy)*100;
			DA = Float.parseFloat(df.format(DA));
			DQ = Float.parseFloat(df.format(DQ));
			fineActionPostion.clear();
			fineActionPostion.put("DA", DA);
			fineActionPostion.put("CA", CA);
			fineActionPostion.put("DQ", DQ);
			fineActionPostion.put("level", this.matchlevel(DQ));
			postions.put("fineActionPostion", fineActionPostion);
			//适应能力
			DA = calculate(times,jsons.getJSONObject("adaptabilityPostion"),postionIds);
			if("NaN".equals(DA+"")) {
				DA = 0;
			}
			DQ =(DA/CACopy)*100;
			DA = Float.parseFloat(df.format(DA));
			DQ = Float.parseFloat(df.format(DQ));
			adaptabilityPostion.clear();
			adaptabilityPostion.put("DA", DA);
			adaptabilityPostion.put("CA", CA);
			adaptabilityPostion.put("DQ", DQ);
			adaptabilityPostion.put("level", this.matchlevel(DQ));
			postions.put("adaptabilityPostion", adaptabilityPostion);
			//语言
			DA = calculate(times,jsons.getJSONObject("languagePostion"),postionIds);
			if("NaN".equals(DA+"")) {
				DA = 0;
			}
			DQ =(DA/CACopy)*100;
			DA = Float.parseFloat(df.format(DA));
			DQ = Float.parseFloat(df.format(DQ));
			languagePostion.clear();
			languagePostion.put("DA", DA);
			languagePostion.put("CA", CA);
			languagePostion.put("DQ", DQ);
			languagePostion.put("level", this.matchlevel(DQ));
			postions.put("languagePostion", languagePostion);
			//社交行为
			DA = calculate(times,jsons.getJSONObject("personalPostion"),postionIds);
			if("NaN".equals(DA+"")) {
				DA = 0;
			}
			DQ =(DA/CACopy)*100;
			DA = Float.parseFloat(df.format(DA));
			DQ = Float.parseFloat(df.format(DQ));
			personalPostion.clear();
			personalPostion.put("DA", DA);
			personalPostion.put("CA", CA);
			personalPostion.put("DQ", DQ);
			personalPostion.put("level", this.matchlevel(DQ));
			postions.put("personalPostion", personalPostion);
			return postions;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	//获取得分
	public Map<String, Object> match(String [] times,String project,Map<String, Object> allPostion,Jedis jedis){
		for (int i = 0; i < times.length - 1; i++) {
			// 获取年龄组的全部行为
			ArrayList<String> titlesList = new ArrayList<String>();
			String key = "Gesell_" + times[i] + "_" + project;
			List<String> lists = JSON.parseArray(jedis.hmget("ExaminationPaper", key).get(0),String.class);
			titlesList.addAll(lists);
			allPostion.put(times[i], titlesList);
			}
		return allPostion;
	}

	//获取起点和终点，并计算智龄
	public float calculate(String [] times ,JSONObject allPostion,Map<String, Object> postionIds) {
		Map<String, Integer> passNum = new LinkedHashMap<>();
		boolean isStart = true;
		// 起点所在的坐标
		int index = 0, start = 0;
		int plusStart1 = 0, indexvalue1 = 0 ,index3=0,index4=0,pass1=0 ;
		while (index < times.length) {
			int pass = 0;
			//获取起点的
			int plusStart=0;
			JSONArray ids = (JSONArray) allPostion.get(times[index]);
			for (Object id : ids) {
				String value = (String) ((Map<String, Object>) postionIds).get(id);
				if (value == null|| (!value.equals("+") && !value.equals("++") && !value.equals("N"))) {
				} else if(value.equals("+")) {
					pass++;
					plusStart++;
				}else {
					pass++;
				}
			}
			if (isStart && ids.size() == pass) {
				start = index;
				//进来一次说明已经找到起点，后续不用进来了
				isStart = false;
				//将得“+”的次数记录下来后期有用
				plusStart1 = plusStart;
				//所有通过的次数包括“+”、“N”、“++”
				pass1= pass;
				//下一个相邻的年龄大能区的数据
				if((index+1)<times.length) {
					//选择“+”
					int indexvalue=0;
					//选择“-”
					int index1=0;
					//选择“+”，"++"，“N”
					int index2=0;
					ids = (JSONArray) allPostion.get(times[index+1]);
					for (Object id : ids) {
						String value = (String) ((Map<String, Object>) postionIds).get(id);
						if (value == null|| (!value.equals("+") && !value.equals("++") && !value.equals("N"))) {
						} else if(value.equals("+")) {
							indexvalue++;
							index2++;
						}else if(value.equals("-")) {
							index1 ++;
						}else {
							index2++;
						}
					}
					indexvalue1 = indexvalue;
					index3 = index1;
					index4 = index2;
				}
			}
			passNum.put(times[index], pass);
			index++;
		}

		//发育龄
		float DA = 0;
		//选择+和N和++的个数
		int molecular=0;
		//判断起点是否是最后一个年龄段
		if(start<times.length-1) {
			//gesell计算第一种情况
			JSONArray jsonArray = (JSONArray) allPostion.get(times[start+1]);
			float InDesign =  (float)jsonArray.size()/2;
			//判断“+”起点相邻的年龄段 (+)个数是否<1/2项目总数（该年龄段）满足条件起点月龄中（+和N和++都算)
			if (indexvalue1<InDesign) {
				// 出生月份，将月份转成周龄
				DA = Float.parseFloat(times[start]) * 30 / 7;
				//获取到
				molecular = passNum.get(times[start]);
				DA = DA*molecular;
				for (int i = start + 1; i < times.length - 1; i++) {
					molecular += passNum.get(times[i]);
					DA = DA+(Float.parseFloat(times[i]) * 30 / 7)*passNum.get(times[i]);
				}
			}else if(indexvalue1>=InDesign) {
			//判断“+”起点相邻的年龄段 (+)个数是否≥1/2项目总数（该年龄段）满足条件起点月龄中（++和N都不算)
				// 出生月份
				DA = Float.parseFloat(times[start]) * 30 / 7;
				molecular = plusStart1;
				DA = DA*molecular;
				for (int i = start + 1; i < times.length - 1; i++) {
					molecular += passNum.get(times[i]);
					DA = DA+(Float.parseFloat(times[i]) * 30 / 7)*passNum.get(times[i]);
				}
			}else if(index4>=InDesign&&pass1<index3) {
			//判断“+”起点相邻的年龄段 (+)个数是否≥1/2项目总数（该年龄段）但（-）多于起点的（+）数满足条件起点月龄中（++和N都算)
				// 出生月份
				DA = Float.parseFloat(times[start]) * 30 / 7;
				molecular = passNum.get(times[start]);
				DA = DA*molecular;
				for (int i = start + 1; i < times.length - 1; i++) {
					molecular += passNum.get(times[i]);
					DA = DA+(Float.parseFloat(times[i]) * 30 / 7)*passNum.get(times[i]);
				}
			}
		}else {
			// 出生月份，将月份转成周龄
			DA = Float.parseFloat(times[start]) * 30 / 7;
			//获取到
			molecular = passNum.get(times[start]);
			DA = DA*molecular;
		}
		return DA/molecular;
   }

	@Override
	public Map<String, Object> getTemperamentScore(Date date, Map<String,Object> map)
			throws Exception {
		Map<String, Object> resultsMap = new LinkedHashMap<>(); // 返回结果
		// 第一步.合成评估算法需要的标准参数(注：reverseEntry=反向条目，positiveEntry=正向条目，entryNum=条目数，mean=平均数，s=标准差)
		int day = DateUtil.daysBetween(date, new Date());
		int month = day % 30 > 15 ? day / 30 + 1 : day / 30;
		if (month < 1 || month > 36) {
			resultsMap.put("success", false);
			resultsMap.put("msg", "宝宝年龄不在气质测量的范围内。");
			return resultsMap;
		}
		Map<String, Map<String, Object>> standardMap = createTemperamentStandard(month);

		// 第二步：获取各维度得分
		Map<String, Object> activityLevel = standardMap.get("activityLevel");
		Map<String, Object> rhythmic = standardMap.get("rhythmic");
		Map<String, Object> dodge = standardMap.get("dodge");
		Map<String, Object> adaptive = standardMap.get("adaptive");
		Map<String, Object> intensityReaction = standardMap.get("intensityReaction");
		Map<String, Object> mood = standardMap.get("mood");
		Map<String, Object> persistence = standardMap.get("persistence");
		Map<String, Object> attentionScattered = standardMap.get("attentionScattered");
		Map<String, Object> reactionThreshold = standardMap.get("reactionThreshold");
		int min = 0, max = 0;
		float activityLevelScore = getTemperamentDimensionScore(activityLevel,map);
		if (max < activityLevelScore)
			max = (int) activityLevelScore;
		if (min > activityLevelScore)
			min = (int) activityLevelScore;
		float rhythmicScore = getTemperamentDimensionScore(rhythmic, map);
		if (max < rhythmicScore)
			max = (int) rhythmicScore;
		if (min > rhythmicScore)
			min = (int) rhythmicScore;
		float dodgeScore = getTemperamentDimensionScore(dodge, map);
		if (max < dodgeScore)
			max = (int) dodgeScore;
		if (min > dodgeScore)
			min = (int) dodgeScore;
		float adaptiveScore = getTemperamentDimensionScore(adaptive, map);
		if (max < adaptiveScore)
			max = (int) adaptiveScore;
		if (min > adaptiveScore)
			min = (int) adaptiveScore;
		float intensityReactionScore = getTemperamentDimensionScore(
				intensityReaction, map);
		if (max < intensityReactionScore)
			max = (int) intensityReactionScore;
		if (min > intensityReactionScore)
			min = (int) intensityReactionScore;
		float moodScore = getTemperamentDimensionScore(mood, map);
		if (max < moodScore)
			max = (int) moodScore;
		if (min > moodScore)
			min = (int) moodScore;
		float persistenceScore = getTemperamentDimensionScore(persistence, map);
		if (max < persistenceScore)
			max = (int) persistenceScore;
		if (min > persistenceScore)
			min = (int) persistenceScore;
		float attentionScatteredScore = getTemperamentDimensionScore(
				attentionScattered, map);
		if (max < attentionScatteredScore)
			max = (int) attentionScatteredScore;
		if (min > attentionScatteredScore)
			min = (int) attentionScatteredScore;
		float reactionThresholdScore = getTemperamentDimensionScore(
				reactionThreshold, map);
		if (max < reactionThresholdScore)
			max = (int) reactionThresholdScore;
		if (min > reactionThresholdScore)
			min = (int) reactionThresholdScore;
		resultsMap.put("activityLevelScore", activityLevelScore);
		resultsMap.put("rhythmicScore", rhythmicScore);
		resultsMap.put("dodgeScore", dodgeScore);
		resultsMap.put("adaptiveScore", adaptiveScore);
		resultsMap.put("intensityReactionScore", intensityReactionScore);
		resultsMap.put("moodScore", moodScore);
		resultsMap.put("persistenceScore", persistenceScore);
		resultsMap.put("attentionScatteredScore", attentionScatteredScore);
		resultsMap.put("reactionThresholdScore", reactionThresholdScore);
		resultsMap.put("min", min - 1);
		resultsMap.put("max", max + 1);

		// 第三步：气质类型判定标准算法，返回评估结果
		float activityLevelMean = (float) activityLevel.get("mean");
		float rhythmicMean = (float) rhythmic.get("mean");
		float dodgeMean = (float) dodge.get("mean");
		float adaptiveMean = (float) adaptive.get("mean");
		float intensityReactionMean = (float) intensityReaction.get("mean");
		float moodMean = (float) mood.get("mean");
		float activityLevelS = (float) activityLevel.get("s");
		float rhythmicS = (float) rhythmic.get("s");
		float dodgeS = (float) dodge.get("s");
		float adaptiveS = (float) adaptive.get("s");
		float intensityReactionS = (float) intensityReaction.get("s");
		float moodS = (float) mood.get("s");

		/*//以上几个维度的平均值和标准差
		//依次为：活动水平、节律性、趋避性、适应性、反应强度、心境、持久性、注意分散、反应阈
		String activityLevelAverage = activityLevelMean+"±"+activityLevelS;
		String rhythmicAverage = rhythmicMean+"±"+rhythmicS;
		String dodgeAverage = dodgeMean+"±"+dodgeS;
		String adaptiveAverage = adaptiveMean+"±"+adaptiveS;
		String intensityReactionAverage = intensityReactionMean+"±"+intensityReactionS;
		String moodAverage = moodMean+"±"+moodS;
		String persistenceAverage = persistence.get("mean")+"±"+persistence.get("s");
		String attentionScatteredAverage = attentionScattered.get("mean")+"±"+attentionScattered.get("s");
		String reactionThresholdAverage = reactionThreshold.get("mean")+"±"+reactionThreshold.get("s");

		resultsMap.put("activityLevelAverage", activityLevelAverage);
		resultsMap.put("rhythmicAverage", rhythmicAverage);
		resultsMap.put("dodgeAverage", dodgeAverage);
		resultsMap.put("adaptiveAverage", adaptiveAverage);
		resultsMap.put("intensityReactionAverage", intensityReactionAverage);
		resultsMap.put("moodAverage", moodAverage);
		resultsMap.put("persistenceAverage", persistenceAverage);
		resultsMap.put("attentionScatteredAverage", attentionScatteredAverage);
		resultsMap.put("reactionThresholdAverage", reactionThresholdAverage);
		*/
		String type = "'中间型'";
		// exceedMeanNum=超过平均数的维度数， exceedSNum=大于一个标准差的维度数
		int exceedMeanNum = 0, exceedSNum = 0;
		boolean isDodgeS = false, isAdaptiveS = false, isIntensityReactionMean = false;
		// 在节律性、趋避性、适应性、反应强度、心境五个维度中，大于平均值的维度
		if (rhythmicScore > rhythmicMean) {//节律性
			exceedMeanNum++;
		}
		if (dodgeScore > dodgeMean) {//趋避性
			exceedMeanNum++;
		}
		if (adaptiveScore > adaptiveMean) {//适应性
			exceedMeanNum++;
		}
		if (intensityReactionScore > intensityReactionMean) {//反应强度
			exceedMeanNum++;
			isIntensityReactionMean = true;
		}
		if (moodScore > moodMean) {//心境
			exceedMeanNum++;
		}
		// 在节律性、趋避性、适应性、反应强度、心境五个维度中，大于一个标准差
		if (rhythmicScore > (rhythmicMean + rhythmicS)) {
			exceedSNum++;
		}
		if (dodgeScore > (dodgeMean + dodgeS)) {
			exceedSNum++;
			isDodgeS = true;
		}
		if (adaptiveScore > (adaptiveMean + adaptiveS)) {
			exceedSNum++;
			isAdaptiveS = true;
		}
		if (intensityReactionScore > (intensityReactionMean + intensityReactionS)) {
			exceedSNum++;
		}
		if (moodScore > (moodMean + moodS)) {
			exceedSNum++;
		}

		// 在节律性、趋避性、适应性、反应强度、心境五个维度中，大于平均值的维度不超过两项，必须没有一个维度大于一个标准差(≤mean+1s)
		if (exceedMeanNum <= 2 && exceedSNum == 0) {
			type = "'易养型'";
		}
		// 在节律性、趋避性、适应性、反应强度、心境五个维度中，4或5个维度得分大于平均值(>mean)，必须包括反应强度；并且其中两个维度得分大于一个标准差(>mean+1s)
		else if ((exceedMeanNum == 4 || exceedMeanNum == 5) && isIntensityReactionMean && exceedSNum == 2) {
			type = "'难养型'";
		}
		// 在节律性、趋避性、适应性、反应强度、心境五个维度中，4或5个维度得分大于平均值(>mean)。且趋避性或适应性必须大于一个标准差(>mean+1s)
		else if ((exceedMeanNum == 4 || exceedMeanNum == 5)&& (isDodgeS || isAdaptiveS)) {
			// 活动水平不高出1/2标准差（≤mean+1/2s）
			boolean isActivityLevel = activityLevelScore <= (activityLevelMean + activityLevelS / 2) ? true
					: false;
			// 心境得分不低于1/2个标准差（≥mean-1/2s）
			boolean isMood = moodScore >= (moodMean - moodS / 2) ? true : false;
			if (isActivityLevel && isMood)
				type = "'发动缓慢型'";
		}
		resultsMap.put("type", type);
		return resultsMap;
		// return examinationPaperDAO.getTemperamentScore(map);
	}

	/**
	 * Name: 或取对应维度的得分 Params: dimension： 各维度中的标准 postions： 前端传递的结果
	 */
	public float getTemperamentDimensionScore(Map<String, Object> dimension,Map<String,Object> postions) {
		String[] reverseEntry = (String[]) dimension.get("reverseEntry"); // 反向条目中题目Id集合
		String[] positiveEntry = (String[]) dimension.get("positiveEntry"); // 正向条目中题目Id集合
		int entryNum = (int) dimension.get("entryNum"); // 该维度条目数
		float reverseScore = 0, positiveScore = 0; // 正/反向/维度得分
		String tempID; // 题目ID
		// 获取正、负向条目得分
		for (int i = 0; i < reverseEntry.length; i++) {
			Object tempScore;
			if (postions.get("0") == null)
				tempID = reverseEntry[i];
			else
				tempID = (Integer.parseInt(reverseEntry[i]) - 1) + "";// 由于word读数据原因，一些题目编号从0开始了，需-1
			tempScore = postions.get(tempID);
			if (tempScore != null)
				reverseScore += Float.parseFloat((String) tempScore);
		}
		reverseScore = 7 - reverseScore;
		for (int i = 0; i < positiveEntry.length; i++) {
			Object tempScore;
			if (postions.get("0") == null)
				tempID = positiveEntry[i];
			else
				tempID = (Integer.parseInt(positiveEntry[i]) - 1) + "";// 由于word读数据原因，一些题目编号从0开始了，需-1
			tempScore = postions.get(tempID);
			if (tempScore != null)
				positiveScore += Float.parseFloat((String) tempScore);
		}
		// 维度得分
		return (reverseScore + positiveScore) / entryNum;
	}

	/**
	 * Name: 创建评估标准 Params: month： 宝宝月龄
	 */
	public Map<String, Map<String, Object>> createTemperamentStandard(int month) {
		Map<String, Map<String, Object>> resultsMap = new LinkedHashMap<String, Map<String, Object>>();
		Map<String, Object> activityLevel = new LinkedHashMap<String, Object>(); // 活动水平
		Map<String, Object> rhythmic = new LinkedHashMap<String, Object>(); // 节律性
		Map<String, Object> dodge = new LinkedHashMap<String, Object>(); // 趋避性
		Map<String, Object> adaptive = new LinkedHashMap<String, Object>(); // 适应性
		Map<String, Object> intensityReaction = new LinkedHashMap<String, Object>(); // 反应强度
		Map<String, Object> mood = new LinkedHashMap<String, Object>(); // 心境
		Map<String, Object> persistence = new LinkedHashMap<String, Object>(); // 持久性
		Map<String, Object> attentionScattered = new LinkedHashMap<String, Object>(); // 注意分散
		Map<String, Object> reactionThreshold = new LinkedHashMap<String, Object>(); // 反应阈

		if (1 <= month && month <= 4) {
			// 活动水平：反向条目 1/10/28/62；正向条目19/37/46/55（条目数=8）
			activityLevel.put("reverseEntry", new String[] { "1", "10", "28","62" });
			activityLevel.put("positiveEntry", new String[] { "19", "37", "46","55" });
			activityLevel.put("entryNum", 8);
			// 节律性：反向条目 2/11/20/56/72；正向条目29/38//47/63/68（条目数=10）
			rhythmic.put("reverseEntry", new String[] { "2", "11", "20", "56","72" });
			rhythmic.put("positiveEntry", new String[] { "29", "38", "47","63", "68" });
			rhythmic.put("entryNum", 10);
			// 趋避性：反向条目48；正向条目3/12/21/30/39（条目数=6）
			dodge.put("reverseEntry", new String[] { "48" });
			dodge.put("positiveEntry", new String[] { "3", "12", "21", "30","39" });
			dodge.put("entryNum", 6);
			// 适应性：反向条目 4/22/31/57/73；正向条目13/40/49/64/69（条目数=10）
			adaptive.put("reverseEntry", new String[] { "4", "22", "31", "57","73" });
			adaptive.put("positiveEntry", new String[] { "13", "40", "49","64", "69" });
			adaptive.put("entryNum", 10);
			// 反应强度：反向条目 无 ；正向条目5/14/23/32/41/50（条目数=6）
			intensityReaction.put("reverseEntry", new String[] {});
			intensityReaction.put("positiveEntry", new String[] { "5", "14","23", "32", "41", "50" });
			intensityReaction.put("entryNum", 6);
			// 心境：反向条目15/51/65/70/74；正向条目6/24/33/42/58/76（条目数=11）
			mood.put("reverseEntry", new String[] { "15", "51", "65", "70","74" });
			mood.put("positiveEntry", new String[] { "6", "24", "33", "42","58", "76" });
			mood.put("entryNum", 11);
			// 持久性：反向条目7/16/25/34/43/52/66；正向条目59（条目数=8）
			persistence.put("reverseEntry", new String[] { "7", "16", "25","34", "43", "52", "66" });
			persistence.put("positiveEntry", new String[] { "59" });
			persistence.put("entryNum", 8);
			// 注意分散：反向条目35/44/53；正向条目8/17/26/60（条目数=7）
			attentionScattered.put("reverseEntry", new String[] { "35", "44","53" });
			attentionScattered.put("positiveEntry", new String[] { "8", "17","26", "60" });
			attentionScattered.put("entryNum", 7);
			// 反应阈：反向条目71；正向条目9/18/27/36/45/54/61/67/75（条目数=10）
			reactionThreshold.put("reverseEntry", new String[] { "71" });
			reactionThreshold.put("positiveEntry", new String[] { "9", "18","27", "36", "45", "54", "61", "67", "75" });
			reactionThreshold.put("entryNum", 10);

			if (1 <= month && month <= 2) {
				activityLevel.put("mean", 3.68f);
				activityLevel.put("s", 0.66f);
				rhythmic.put("mean", 3.64f);
				rhythmic.put("s", 0.66f);
				dodge.put("mean", 2.45f);
				dodge.put("s", 0.79f);
				adaptive.put("mean", 2.67f);
				adaptive.put("s", 0.62f);
				intensityReaction.put("mean", 3.80f);
				intensityReaction.put("s", 0.78f);
				mood.put("mean", 3.32f);
				mood.put("s", 0.56f);
				persistence.put("mean", 3.19f);
				persistence.put("s", 0.74f);
				attentionScattered.put("mean", 2.90f);
				attentionScattered.put("s", 0.72f);
				reactionThreshold.put("mean", 4.16f);
				reactionThreshold.put("s", 0.65f);
			} else {
				activityLevel.put("mean", 3.87f);
				activityLevel.put("s", 0.72f);
				rhythmic.put("mean", 3.41f);
				rhythmic.put("s", 0.66f);
				dodge.put("mean", 2.77f);
				dodge.put("s", 0.92f);
				adaptive.put("mean", 2.53f);
				adaptive.put("s", 0.64f);
				intensityReaction.put("mean", 3.75f);
				intensityReaction.put("s", 0.81f);
				mood.put("mean", 2.84f);
				mood.put("s", 0.61f);
				persistence.put("mean", 2.67f);
				persistence.put("s", 0.78f);
				attentionScattered.put("mean", 2.68f);
				attentionScattered.put("s", 0.82f);
				reactionThreshold.put("mean", 4.27f);
				reactionThreshold.put("s", 0.70f);
			}
		} else if (4 < month && month < 12) {
			// 活动水平：反向条目4/12/30/55/79/86；正向条目17/33/43/51/64/71/95（条目数=13）
			activityLevel.put("reverseEntry", new String[] { "4", "12", "30","55", "79", "86" });
			activityLevel.put("positiveEntry", new String[] { "17", "33", "43","51", "64", "71", "95" });
			activityLevel.put("entryNum", 13);
			// 节律性：反向条目 1/13/28/50/60/73/85；正向条目20/35/46/67/77（条目数=12）
			rhythmic.put("reverseEntry", new String[] { "1", "13", "28", "50","60", "73", "85" });
			rhythmic.put("positiveEntry", new String[] { "20", "35", "46","67", "77" });
			rhythmic.put("entryNum", 12);
			// 趋避性：反向条目5/24/45/62/82；正向条目14/31/36/66/74/91（条目数=11）
			dodge.put("reverseEntry", new String[] { "5", "24", "45", "62","82" });
			dodge.put("positiveEntry", new String[] { "14", "31", "36", "66","74", "91" });
			dodge.put("entryNum", 11);
			// 适应性：反向条目6/9/29/49/56/94；正向条目19/34/65/78/90（条目数=11）
			adaptive.put("reverseEntry", new String[] { "6", "9", "29", "49","56", "94" });
			adaptive.put("positiveEntry", new String[] { "19", "34", "65","78", "90" });
			adaptive.put("entryNum", 11);
			// 反应强度：反向条目 10/26/75/84/89；正向条目18/38/42/54/70（条目数=10）
			intensityReaction.put("reverseEntry", new String[] { "10", "26","75", "84", "89" });
			intensityReaction.put("positiveEntry", new String[] { "18", "38","42", "54", "70" });
			intensityReaction.put("entryNum", 10);
			// 心境：反向条目 23/27/39/61/63/81；正向条目2/48/76/93（条目数=10）
			mood.put("reverseEntry", new String[] { "23", "27", "39", "61","63", "81" });
			mood.put("positiveEntry", new String[] { "2", "48", "76", "93" });
			mood.put("entryNum", 10);
			// 持久性：反向条目 8/16/32/41/58；正向条目3/25/88（条目数=8）
			persistence.put("reverseEntry", new String[] { "8", "16", "32","41", "58" });
			persistence.put("positiveEntry", new String[] { "3", "25", "88" });
			persistence.put("entryNum", 8);
			// 注意分散：反向条目 7/21/44/53/59/80/87；正向条目15/40/68（条目数=10）
			attentionScattered.put("reverseEntry", new String[] { "7", "21","44", "53", "59", "80", "87" });
			attentionScattered.put("positiveEntry", new String[] { "15", "40","68" });
			attentionScattered.put("entryNum", 10);
			// 反应阈：反向条目 22/47/72/92；正向条目11/37/52/57/69/83（条目数=10）
			reactionThreshold.put("reverseEntry", new String[] { "22", "47","72", "92" });
			reactionThreshold.put("positiveEntry", new String[] { "11", "37","52", "57", "69", "83" });
			reactionThreshold.put("entryNum", 10);

			activityLevel.put("mean", 3.69f);
			activityLevel.put("s", 0.62f);
			rhythmic.put("mean", 3.09f);
			rhythmic.put("s", 0.70f);
			dodge.put("mean", 2.91f);
			dodge.put("s", 0.81f);
			adaptive.put("mean", 2.94f);
			adaptive.put("s", 0.69f);
			intensityReaction.put("mean", 3.59f);
			intensityReaction.put("s", 0.66f);
			mood.put("mean", 3.37f);
			mood.put("s", 0.70f);
			persistence.put("mean", 3.21f);
			persistence.put("s", 0.78f);
			attentionScattered.put("mean", 2.91f);
			attentionScattered.put("s", 0.66f);
			reactionThreshold.put("mean", 3.88f);
			reactionThreshold.put("s", 0.68f);
		} else if (12 <= month && month <= 36) {
			// 活动水平：反向条目12/18/64/73/85/90；正向条目2/24/36/47/52/58（条目数=12）
			activityLevel.put("reverseEntry", new String[] { "12", "18", "64","73", "85", "90" });
			activityLevel.put("positiveEntry", new String[] { "2", "24", "36","47", "52", "58" });
			activityLevel.put("entryNum", 12);
			// 节律性：反向条目 1/30/59/77/82；正向条目7/17/33/42/54/68（条目数=11）
			rhythmic.put("reverseEntry", new String[] { "1", "30", "59", "77","82" });
			rhythmic.put("positiveEntry", new String[] { "7", "17", "33", "42","54", "68" });
			rhythmic.put("entryNum", 11);
			// 趋避性：反向条目 5/21/26/38/45/57/76/96；正向条目9/53/87/94（条目数=12）
			dodge.put("reverseEntry", new String[] { "5", "21", "26", "38","45", "57", "76", "96" });
			dodge.put("positiveEntry", new String[] { "9", "53", "87", "94" });
			dodge.put("entryNum", 12);
			// 适应性：反向条目 11/32/56/60/65；正向条目44/78/88/93（条目数=9）
			adaptive.put("reverseEntry", new String[] { "11", "32", "56", "60","65" });
			adaptive.put("positiveEntry",new String[] { "44", "78", "88", "93" });
			adaptive.put("entryNum", 9);
			// 反应强度：反向条目 3/55/70；正向条目14/19/29/35/46/74/83（条目数=10）
			intensityReaction.put("reverseEntry", new String[] { "3", "55","70" });
			intensityReaction.put("positiveEntry", new String[] { "14", "19","29", "35", "46", "74", "83" });
			intensityReaction.put("entryNum", 10);
			// 心境：反向条目 4/31/43/63/75；正向条目8/20/25/49/69/84/89/95（条目数=13）
			mood.put("reverseEntry",new String[] { "4", "31", "43", "63", "75" });
			mood.put("positiveEntry", new String[] { "8", "20", "25", "49","69", "84", "89", "95" });
			mood.put("entryNum", 13);
			// 持久性：反向条目 15/28/62/71/79/91；正向条目6/34/40/51/86（条目数=11）
			persistence.put("reverseEntry", new String[] { "15", "28", "62","71", "79", "91" });
			persistence.put("positiveEntry", new String[] { "6", "34", "40","51", "86" });
			persistence.put("entryNum", 11);
			// 注意分散：反向条目 13/37/41/50/66；正向条目22/27/61/72/81/97（条目数=11）
			attentionScattered.put("reverseEntry", new String[] { "13", "37","41", "50", "66" });
			attentionScattered.put("positiveEntry", new String[] { "22", "27","61", "72", "81", "97" });
			attentionScattered.put("entryNum", 11);
			// 反应阈：反向条目 16/23/39/67/80/92；正向条目10/48（条目数=8）
			reactionThreshold.put("reverseEntry", new String[] { "16", "23","39", "67", "80", "92" });
			reactionThreshold.put("positiveEntry", new String[] { "10", "48" });
			reactionThreshold.put("entryNum", 8);

			activityLevel.put("mean", 3.66f);
			activityLevel.put("s", 0.59f);
			rhythmic.put("mean", 2.97f);
			rhythmic.put("s", 0.60f);
			dodge.put("mean", 3.32f);
			dodge.put("s", 0.82f);
			adaptive.put("mean", 3.34f);
			adaptive.put("s", 0.60f);
			intensityReaction.put("mean", 3.91f);
			intensityReaction.put("s", 0.68f);
			mood.put("mean", 3.07f);
			mood.put("s", 0.59f);
			persistence.put("mean", 3.17f);
			persistence.put("s", 0.71f);
			attentionScattered.put("mean", 3.33f);
			attentionScattered.put("s", 0.64f);
			reactionThreshold.put("mean", 2.02f);
			reactionThreshold.put("s", 0.76f);
		}

		resultsMap.put("activityLevel", activityLevel);
		resultsMap.put("rhythmic", rhythmic);
		resultsMap.put("dodge", dodge);
		resultsMap.put("adaptive", adaptive);
		resultsMap.put("intensityReaction", intensityReaction);
		resultsMap.put("mood", mood);
		resultsMap.put("persistence", persistence);
		resultsMap.put("attentionScattered", attentionScattered);
		resultsMap.put("reactionThreshold", reactionThreshold);
		return resultsMap;
	}

	@Override
	public Map<String, Object> getSmallWechslerScore(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);
			Map<String, Object> scoreMap = new HashMap<String, Object>();
			int language = 0, operation = 0, all = 0;
			int month = 0;
			int day = Integer.parseInt(map.get("day").toString());
			day = 3 * 365 + 10 * 30 + 18;
			if (3 * 365 + 10 * 30 + 16 <= day && day <= 4 * 365 + 1 * 30 + 15)
				month = 48;
			else if (4 * 365 + 1 * 30 + 16 <= day && day <= 4 * 365 + 4 * 30 + 15)
				month = 51;
			else if (4 * 365 + 4 * 30 + 16 <= day && day <= 4 * 365 + 7 * 30 + 15)
				month = 54;
			else if (4 * 365 + 7 * 30 + 16 <= day && day <= 4 * 365 + 10 * 30 + 15)
				month = 57;
			else if (4 * 365 + 10 * 30 + 16 <= day && day <= 5 * 365 + 1 * 30 + 15)
				month = 60;
			else if (5 * 365 + 1 * 30 + 16 <= day && day <= 5 * 365 + 4 * 30 + 15)
				month = 63;
			else if (5 * 365 + 4 * 30 + 16 <= day && day <= 5 * 365 + 7 * 30 + 15)
				month = 66;
			else if (5 * 365 + 7 * 30 + 16 <= day && day <= 5 * 365 + 10 * 30 + 15)
				month = 69;
			else if (5 * 365 + 10 * 30 + 16 <= day && day <= 6 * 365 + 1 * 30 + 15)
				month = 72;
			else if (6 * 365 + 1 * 30 + 16 <= day && day <= 6 * 365 + 4 * 30 + 15)
				month = 75;
			else if (6 * 365 + 4 * 30 + 16 <= day && day <= 6 * 365 + 7 * 30 + 15)
				month = 78;
			else {
				scoreMap.put("success", false);
				return scoreMap;
			}
			// 根据原始分算出量表分
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				int value = 0;
				String key = "SmallWechsler_" + month + "_" + entry.getKey();
				Map<String, Object> score = new HashMap<String, Object>();
				String allScore = jedis.hmget("Criteria", key).get(0);
				if (allScore != null)
					score = ToolUtils.stringToMap(allScore);
				for (Map.Entry<String, Object> e : score.entrySet()) {
					if (e.getValue().toString().contains("-")) {
						String[] str = e.getValue().toString().split("-");
						int start = Integer.parseInt(str[0]), end = Integer.parseInt(str[1]);
						for (int i = start; i < end; i++) {
							if (i == (int) entry.getValue()) {
								value = Integer.parseInt(e.getKey());
								break;
							}
						}
					} else {
						if (e.getValue().toString().equals(entry.getValue().toString())) {
							value = Integer.parseInt(e.getKey());
							break;
						}
					}
				}
				String type = entry.getKey().toString();
				if (type.equals("常识") || type.equals("词汇") || type.equals("算术题") || type.equals("类同词")|| type.equals("理解")) {
					language += value;
				} else {
					operation += value;
				}
				all += value;
				scoreMap.put(entry.getKey(), value);
			}
			scoreMap.put("语言量表分", language);
			scoreMap.put("操作量表分", operation);
			scoreMap.put("总量表分", all);

			// 根据量表分算出智
			Map<String, Object> languageMap = new HashMap<String, Object>();
			String languageScore = jedis.hmget("Criteria","SmallWechsler_small_language").get(0);
			if (languageScore != null)
				languageMap = ToolUtils.stringToMap(languageScore);
			for (Map.Entry<String, Object> entry : languageMap.entrySet()) {
				if (entry.getKey().toString().equals(language + "")) {
					language = Integer.parseInt(entry.getValue().toString());
					break;
				}
			}
			Map<String, Object> operationMap = new HashMap<String, Object>();
			String operationScore = jedis.hmget("Criteria","SmallWechsler_small_operation").get(0);
			if (operationScore != null)
				operationMap = ToolUtils.stringToMap(operationScore);
			for (Map.Entry<String, Object> entry : operationMap.entrySet()) {
				if (entry.getKey().toString().equals(operation + "")) {
					operation = Integer.parseInt(entry.getValue().toString());
					break;
				}
			}
			Map<String, Object> allMap = new HashMap<String, Object>();
			String allScore = jedis.hmget("Criteria", "SmallWechsler_small_all").get(0);
			if (allScore != null)
				allMap = ToolUtils.stringToMap(allScore);
			for (Map.Entry<String, Object> entry : allMap.entrySet()) {
				if (entry.getKey().toString().equals(all + "")) {
					all = Integer.parseInt(entry.getValue().toString());
					break;
				}
			}
			scoreMap.put("语言智商", language);
			scoreMap.put("操作智商", operation);
			scoreMap.put("总智商", all);
			scoreMap.put("success", true);

			return scoreMap;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> getBigWechslerScore(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);

			Map<String, Object> scoreMap = new HashMap<String, Object>();
			return scoreMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> getAimsScore(Map<String, Object> map)
			throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();

		Patient pt = (Patient)map.get("patient");
		String postionIds = (String)map.get("postionIds");
		JSONObject postionJson = JSON.parseObject(postionIds);

		//四个模块选择的项目 每项分窗前分和窗内得分
		List<Integer>  proneIds  =  JSON.parseArray(postionJson.getString("prone"), Integer.class);
		List<Integer>  dorsaIds  =  JSON.parseArray(postionJson.getString("dorsa"), Integer.class);
		List<Integer>  seatsIds  =  JSON.parseArray(postionJson.getString("seats"), Integer.class);
		List<Integer>  standIds  =  JSON.parseArray(postionJson.getString("stand"), Integer.class);

		//分项得分
		Map<String,Object> proneMap = new HashMap<String,Object>();
		Map<String,Object> dorsaMap = new HashMap<String,Object>();
		Map<String,Object> seatsMap = new HashMap<String,Object>();
		Map<String,Object> standMap = new HashMap<String,Object>();
		//百分位和总分
		Map<String,Object> totaltMap = new HashMap<String,Object>();

		int preWindowProne = 0,windowProne = 0,preWindowDorsa = 0,windowDorsa = 0,
				preWindowSeats = 0,windowSeats = 0,preWindowStand = 0,windowStand = 0;

		if(!CollectionUtils.isEmpty(proneIds)){
			windowProne = proneIds.size(); //窗内得分
			//窗前得分 == 窗内最小ID  之前题目得分
			preWindowProne = Collections.min(proneIds) - 1;
			if(preWindowProne<0){
				preWindowProne = 0;
			}
		}
		proneMap.put("windowProne",windowProne);
		proneMap.put("preWindowProne",preWindowProne);

		if(!CollectionUtils.isEmpty(dorsaIds)){
			windowDorsa= dorsaIds.size();
			//窗前得分 == 窗内最小ID  之前题目得分
			preWindowDorsa  = Collections.min(dorsaIds) - 1;
			if(preWindowDorsa<0){
				preWindowDorsa = 0;
			}
		}
		dorsaMap.put("windowDorsa",windowDorsa);
		dorsaMap.put("preWindowDorsa",preWindowDorsa);

		if(!CollectionUtils.isEmpty(seatsIds)){
			windowSeats = seatsIds.size();
			//窗前得分 == 窗内最小ID 之前题目得分 每题默认1分
			preWindowSeats  = Collections.min(seatsIds) - 1;
			if(preWindowSeats<0){
				preWindowSeats = 0;
			}
		}
		seatsMap.put("windowSeats",windowSeats);
		seatsMap.put("preWindowSeats",preWindowSeats);

		if(!CollectionUtils.isEmpty(standIds)){
			windowStand = standIds.size();
			//窗前得分 == 窗内最小ID  之前题目得分
			preWindowStand  = Collections.min(standIds) - 1;
			if(preWindowStand<0){
				preWindowStand = 0;
			}
		}
		standMap.put("windowStand",windowStand);
		standMap.put("preWindowStand",preWindowStand);

		rspMap.put("prone",proneMap);
		rspMap.put("dorsa",dorsaMap);
		rspMap.put("seats",seatsMap);
		rspMap.put("stand",standMap);

		int total = preWindowProne+windowProne+preWindowDorsa+windowDorsa+preWindowSeats+windowSeats+preWindowStand+windowStand;

		totaltMap.put("totalScore", total);

		map.put("values",total);
		Map<String,Object> percentMap = getScorePercent(map,pt);
		Object percent =percentMap.get("percentiles");
		totaltMap.put("percent", percent);

		rspMap.put("total",totaltMap);
		return rspMap;
	}

	//计算aims百分位
	private Map<String, Object> getScorePercent(Map<String, Object> paramMap,Patient patient)
			throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();

		String birthday=patient.getBirthday();
		Integer pregnancyDay=patient.getPregnancyDay();

		Long birthLong = ToolUtils.getCorrect(birthday, pregnancyDay);//生日时间戳
		String testTime = (String)paramMap.get("testTime");
		long date = 0;
		if(StringUtils.isEmpty(testTime)){
			date = new Date().getTime();
		}else{
			date = DateUtil.getDate_8(testTime).getTime();
		}
		long ageDay = (date-birthLong)/(1000*60*60*24);

		float month = (float)ageDay/30.0f;
		//查询who标准数据
		Map<String,Object> standMap = new HashMap<String,Object>();
		standMap.put("age",month);
		standMap.put("standardId",Constants.AIMS_STANDARD_ID);
		standMap.put("standardType",Constants.AIMS_STANDARD_TYPE_PERCENT);
		standMap.put("projectId",Constants.AIMS_DEVELOPPROJECT_SCORE);
		//返回超过年龄 无标准数据

		String percentiles ="";
		BsEvaluationStandard standard = followEvaluationDao.selectEvaluationStandardsByAge(standMap);
		if(null != standard){//
//			double sd4neg = (double) whoMaplist.get(0).get("SD4NEG");
			double p5 = standard.getP5();
			double p10 = standard.getP10();
			double p25 = standard.getP25();
			double p50 = standard.getP50();
			double p75 = standard.getP75();
			double p90 = standard.getP90();
			double p95 = standard.getP95();

			int value = Integer.parseInt(String.valueOf(paramMap.get("values")));

			// 50为分隔   50以上  > && <=    50以下 >= && <
			if (month < 8.0F)
			{
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value <= p75)) {
					percentiles = "50%~75%";
				} else if ((value > p75) && (value <= p90)) {
					percentiles = "75%~90%";
				} else if ((value > p90) && (value < p95)) {
					percentiles = "90%~95%";
				} else if (value >= p95) {
					percentiles = "95%~99%";
				}
			}else if ((month >= 8.0F) && (month < 9.0F))
			{
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value <= p75)) {
					percentiles = "50%~75%";
				} else if ((value > p75) && (value <= p90)) {
					percentiles = "75%~90%";
				} else if ((value > p90) && (value < p95)) {
					percentiles = "90%~98%";
				} else if (value >= p95) {
					percentiles = ">98%";
				}
			}else if ((month >= 9.0F) && (month < 10.0F))
			{
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value <= p75)) {
					percentiles = "50%~75%";
				} else if ((value > p75) && (value <= p90)) {
					percentiles = "75%~90%";
				} else if ((value > p90) && (value < p95)) {
					percentiles = "90%~95%";
				} else if (value >= p95) {
					percentiles = ">95%";
				}
			}
			else if ((month >= 10.0F) && (month < 11.0F))
			{
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value <= p75)) {
					percentiles = "50%~75%";
				} else if ((value > p75) && (value <= p90)) {
					percentiles = "75%~90%";
				} else if ((value > p90) && (value < p95)) {
					percentiles = "90%~93%";
				} else if (value >= p95) {
					percentiles = ">93%";
				}
			}
			else if ((month >= 11.0F) && (month < 12.0F))
			{
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value <= p75)) {
					percentiles = "50%~75%";
				} else if ((value > p75) && (value < p90)) {
					percentiles = "75%~83%";
				} else if (value >= p90) {
					percentiles = ">83%";
				}
			}
			else if ((month >= 12.0F) && (month < 13.0F))
			{
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value <= p75)) {
					percentiles = "50%~75%";
				} else if ((value > p75) && (value < p90)) {
					percentiles = "75%~77%";
				} else if (value >= p90) {
					percentiles = ">77%";
				}
			}
			else if ((month >= 13.0F) && (month < 14.0F))
			{
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value < p75)) {
					percentiles = "50%~68%";
				} else if (value >= p75) {
					percentiles = ">68%";
				}
			}
			else if (month >= 14.0F) {
				if (value < p5) {
					percentiles = "<5%";
				} else if ((value >= p5) && (value < p10)) {
					percentiles = "5%~10%";
				} else if ((value >= p10) && (value < p25)) {
					percentiles = "10%~25%";
				} else if ((value >= p25) && (value <= p50)) {
					percentiles = "25%~50%";
				} else if ((value > p50) && (value < p75)) {
					percentiles = "50%~71%";
				} else if (value >= p75) {
					percentiles = ">71%";
				}
			}
		}
		rspMap.put("percentiles",percentiles);
		return rspMap;
	}

	@Override
	public Map<String,Object> getSDQScore(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		String postions = (String)map.get("postionIds");

		String flag = (String)map.get("version");

		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SDQ);
			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_PREGNANT_SDQ);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SDQ,json);
				}
			}

			List<JSONObject> postionList = new ArrayList<JSONObject>();
			JSONArray arr = JSON.parseArray(json);
			for(int i = 0;i<arr.size();i++){
				postionList.add(arr.getJSONObject(i));
			}

			//传入答题 结果
			JSONObject jsonEsb = JSON.parseObject(postions);
//			String normal ="正常",dubious="可疑",abnormal="异常";
			String normal ="发育良好",dubious="低风险",abnormal="风险偏高";
			int prosocial = 0,mbd=0,emotional=0,conduct=0,companion=0,total=0;
			//评分标准：情绪症状 ：0-3	4	5-10  ，品行问题0-2	3	4-10 ，多动0-5	6	7-10，同伴交往0-2	3	4-10，亲社会行为 10-6	5	0-4，困难总分 0-13	14-16	17-40
			Map<String,Object> prosocialMap = new HashMap<String,Object>(),mbdMap = new HashMap<String,Object>(),
					emotionalMap = new HashMap<String,Object>(),conductMap = new HashMap<String,Object>(),
					companionMap = new HashMap<String,Object>(),totalMap = new HashMap<String,Object>();

			//后续修改跟 答题结果循环
			for(int i = 0 ;i<postionList.size();i++){
				String factor = postionList.get(i).getString("factor");
				String id = postionList.get(i).getString("id");
				int number = Integer.parseInt(id);
				if(number <= 25){ //25题 之内算分  附加题暂时不算分obj.getIntValue("id")+1
					String answerId = jsonEsb.getString(id);
					JSONArray answers =  postionList.get(i).getJSONArray("answer");
					if(null != answers && !StringUtils.isEmpty(answerId)){
						for(int j = 0 ;j<answers.size();j++){
							JSONObject obj = answers.getJSONObject(j);
							String idStr  ="";
							if("MABC".equals(flag)){
								idStr= String.valueOf(obj.getIntValue("id"));
							}else{
								idStr = String.valueOf(obj.getIntValue("id")-1);
							}

							if(answerId.equals(idStr)){
								int score = obj.getIntValue("score");
								if(Constants.SDQ_FACTOR_TYPE_COMPANION.equals(factor)){
									companion+=score;
									break;//单选题  匹配一项及退出答案匹配循环
								}else if(Constants.SDQ_FACTOR_TYPE_CONDUCT.equals(factor)){
									conduct+=score;
									break;
								}else if(Constants.SDQ_FACTOR_TYPE_EMOTIONAL.equals(factor)){
									emotional+=score;
									break;
								}else if(Constants.SDQ_FACTOR_TYPE_MBD.equals(factor)){
									mbd+=score;
									break;
								}else if(Constants.SDQ_FACTOR_TYPE_PROSOCIAL.equals(factor)){
									prosocial+=score;
									break;
								}
							}
						}
					}
				}
			}
			total = mbd+emotional+conduct+companion;
			prosocialMap.put("score",prosocial);
			prosocialMap.put("desc","亲社会行为");
			if(prosocial>=6){
				prosocialMap.put("result",normal);
			}else if(prosocial==5){
				prosocialMap.put("result",dubious);
			}else if(prosocial>=0 && prosocial<=4){
				prosocialMap.put("result",abnormal);
			}
			mbdMap.put("score",mbd);
			mbdMap.put("desc","多动");
			if(mbd>=0 && mbd<=5){
				mbdMap.put("result",normal);
			}else if(mbd==6){
				mbdMap.put("result",dubious);
			}else if(mbd>=7){
				mbdMap.put("result",abnormal);
			}
			emotionalMap.put("score",emotional);
			emotionalMap.put("desc","情绪症状");
			if(emotional>=0 && emotional<=3){
				emotionalMap.put("result",normal);
			}else if(emotional==4){
				emotionalMap.put("result",dubious);
			}else if(emotional>=5){
				emotionalMap.put("result",abnormal);
			}
			conductMap.put("score",conduct);
			conductMap.put("desc","品行问题");
			if(conduct>=0 && conduct<=2){
				conductMap.put("result",normal);
			}else if(conduct==3){
				conductMap.put("result",dubious);
			}else if(conduct>=4){
				conductMap.put("result",abnormal);
			}

			companionMap.put("score",companion);
			companionMap.put("desc","同伴交往");
			if(companion>=0 && companion<=2){
				companionMap.put("result",normal);
			}else if(companion==3){
				companionMap.put("result",dubious);
			}else if(companion>=4 &&companion<=10){
				companionMap.put("result",abnormal);
			}

			totalMap.put("score",total);
			totalMap.put("desc","困难总分");
			if(total>=0 && total<=13){
				totalMap.put("result",normal);
			}else if(total>=14 && total<=16){
				totalMap.put("result",dubious);
			}else if(total>=17){
				totalMap.put("result",abnormal);
			}

			Map<String, Object> scoreMap = new HashMap<String, Object>();
			Map<String, Object> scoreDetailMap = new HashMap<String, Object>();
			scoreDetailMap.put("diffTotal",totalMap);
			scoreDetailMap.put("companion",companionMap);
			scoreDetailMap.put("emotional",emotionalMap);
			scoreDetailMap.put("conduct",conductMap);
			scoreDetailMap.put("mbd",mbdMap);
			scoreDetailMap.put("prosocial",prosocialMap);
			scoreMap.put("score", scoreDetailMap);
			scoreMap.put("maxScore","10");
			return scoreMap;

		}catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		}finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> getAhemdScore(Map<String, Object> map)
			throws Exception {
		String postions = (String)map.get("postionIds");
		Patient pt = (Patient)map.get("Patient");
		List<JSONObject> postionList = followEvaluationService.getPregnantCommonPostion(map);//获取问卷
		//传入答题 结果
		JSONObject jsonEsb = JSON.parseObject(postions);
		String lack ="远远不足",moderate="适量",adequate="充足",veryEdequate="非常充足";
		int activitySpace = 0,activityDiversity=0,heavySportsToys=0,fineSportsToys=0,total=0;
		//3-11月 活动空间 :0-1,2-3，4-5,6-7 ;活动多样性 :0-9,10-11,12-13,14-20；精细运动玩具：0-2,3,4-5,6-10 ；粗大运动玩具：0-3,4-5，6-7，8-12
		Map<String,Object> activitySpaceMap = new HashMap<String,Object>(),activityDiversityMap = new HashMap<String,Object>(),
			heavySportsToysMap = new HashMap<String,Object>(),fineSportsToysMap = new HashMap<String,Object>(),
		totalMap = new HashMap<String,Object>();

		//后续修改跟 答题结果循环
		if(!CollectionUtils.isEmpty(postionList)){
			for(int i = 0 ;i<postionList.size();i++){
				String factor = postionList.get(i).getString("activity");
				String id = postionList.get(i).getString("id");
				String answerId = jsonEsb.getString(id);
				JSONArray answers =  postionList.get(i).getJSONArray("answer");
				if(null != answers && !StringUtils.isEmpty(answerId)){
					for(int j = 0 ;j<answers.size();j++){
						JSONObject obj = answers.getJSONObject(j);
						String idStr = obj.getString("id");
						if(answerId.equals(idStr)){
							int score = obj.getIntValue("score");
							if(Constants.AHEMD_TYPE_ACTIVITY_SPACE.equals(factor)){
								activitySpace+=score;
								break;//单选题  匹配一项及退出答案匹配循环
							}else if(Constants.AHEMD_TYPE_ACTIVITY_DIVERSITY.equals(factor)){
								activityDiversity+=score;
								break;
							}else if(Constants.AHEMD_TYPE_HEAVY_SPORT_TOYS.equals(factor)){
								heavySportsToys+=score;
								break;
							}else if(Constants.AHEMD_TYPE_FINE_SPORT_TOYS.equals(factor)){
								fineSportsToys+=score;
								break;
							}
						}
					}
				}
			}
		}

		activitySpaceMap.put("score",activitySpace);
		activitySpaceMap.put("desc","活动空间");
		activityDiversityMap.put("score",activityDiversity);
		activityDiversityMap.put("desc","活动多样性");
		heavySportsToysMap.put("score",heavySportsToys);
		heavySportsToysMap.put("desc","粗大运动玩具");
		fineSportsToysMap.put("score",fineSportsToys);
		fineSportsToysMap.put("desc","精细运动玩具");
		Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
		//20180410
		long ageDay=0;
		String testTime = (String)map.get("testTime");
		if(StringUtils.isEmpty(testTime)){
			ageDay=(new Date().getTime()-birthLong)/(1000*60*60*24);
		}else{
			ageDay=(DateUtil.getDate_8(testTime).getTime()-birthLong)/(1000*60*60*24);
		}
//		int age = ToolUtils.getAgeMonthByBirthday(DateUtil.getDate_8(new Date()),DateUtil.getDate_8(new Date(birthLong)));
		long age = (long) (ageDay/30);
		//可让客户端根据  app用户自己年龄 来判断
		Map<String, Object> scoreMap = new HashMap<String, Object>();
		Map<String, Object> scoreDetailMap = new HashMap<String, Object>();
		if(age <= 11){ //3-11月龄
			scoreMap.put("maxScore","20");
			if(activitySpace>=0 && activitySpace<=1){
				activitySpaceMap.put("result",lack);
			}else if(activitySpace>=2 &&activitySpace<=3){
				activitySpaceMap.put("result",moderate);
			}else if(activitySpace>=4&&activitySpace<=5){
				activitySpaceMap.put("result",adequate);
			}else if(activitySpace>=6 && activitySpace<=7){
				activitySpaceMap.put("result",veryEdequate);
			}

			if(activityDiversity>=0 && activityDiversity<=9){
				activityDiversityMap.put("result",lack);
			}else if(activityDiversity>=10 &&activityDiversity<=11){
				activityDiversityMap.put("result",moderate);
			}else if(activityDiversity>=12&&activityDiversity<=13){
				activityDiversityMap.put("result",adequate);
			}else if(activityDiversity>=14 && activityDiversity<=20){
				activityDiversityMap.put("result",veryEdequate);
			}

			if(heavySportsToys>=0 && heavySportsToys<=3){
				heavySportsToysMap.put("result",lack);
			}else if(heavySportsToys>=4 && heavySportsToys<=5){
				heavySportsToysMap.put("result",moderate);
			}else if(heavySportsToys>=6 && heavySportsToys<=7){
				heavySportsToysMap.put("result",adequate);
			}else if(heavySportsToys>=8 && heavySportsToys<=12){
				heavySportsToysMap.put("result",veryEdequate);
			}

			if(fineSportsToys>=0 && fineSportsToys<=2){
				fineSportsToysMap.put("result",lack);
			}else if(fineSportsToys==3){
				fineSportsToysMap.put("result",moderate);
			}else if(fineSportsToys>=4 && fineSportsToys<=5){
				fineSportsToysMap.put("result",adequate);
			}else if(fineSportsToys>=6 && fineSportsToys<=10){
				fineSportsToysMap.put("result",veryEdequate);
			}

			if(total>=0 && total<=18){
				totalMap.put("result",lack);
			}else if(total>=19 &&total<=23){
				totalMap.put("result",moderate);
			}else if(total>=24&&total<=27){
				totalMap.put("result",adequate);
			}else if(total>=28 && total<=49){
				totalMap.put("result",veryEdequate);
			}
		}else{
			scoreMap.put("maxScore","22");
			if(activitySpace>=0 && activitySpace<=2){
				activitySpaceMap.put("result",lack);
			}else if(activitySpace>=3 &&activitySpace<=4){
				activitySpaceMap.put("result",moderate);
			}else if(activitySpace==5){
				activitySpaceMap.put("result",adequate);
			}else if(activitySpace>=6 && activitySpace<=7){
				activitySpaceMap.put("result",veryEdequate);
			}

			if(activityDiversity>=0 && activityDiversity<=10){
				activityDiversityMap.put("result",lack);
			}else if(activityDiversity>=11 &&activityDiversity<=12){
				activityDiversityMap.put("result",moderate);
			}else if(activityDiversity>=13 &&activityDiversity<=14){
				activityDiversityMap.put("result",adequate);
			}else if(activityDiversity>=15 && activityDiversity<=20){
				activityDiversityMap.put("result",veryEdequate);
			}

			if(heavySportsToys>=0 && heavySportsToys<=6){
				heavySportsToysMap.put("result",lack);
			}else if(heavySportsToys>=7 && heavySportsToys<=8){
				heavySportsToysMap.put("result",moderate);
			}else if(heavySportsToys>=9 &&heavySportsToys<=11){
				heavySportsToysMap.put("result",adequate);
			}else if(heavySportsToys>=12 && heavySportsToys<=18){
				heavySportsToysMap.put("result",veryEdequate);
			}

			if(fineSportsToys>=0 && fineSportsToys<=6){
				fineSportsToysMap.put("result",lack);
			}else if(fineSportsToys>=7 && fineSportsToys<=9){
				fineSportsToysMap.put("result",moderate);
			}else if(fineSportsToys>=10 && fineSportsToys<=14){
				fineSportsToysMap.put("result",adequate);
			}else if(fineSportsToys>=15 && fineSportsToys<=22){
				fineSportsToysMap.put("result",veryEdequate);
			}

			if(total>=0 && total<=27){
				totalMap.put("result",lack);
			}else if(total>=28 &&total<=33){
				totalMap.put("result",moderate);
			}else if(total>=34&&total<=40){
				totalMap.put("result",adequate);
			}else if(total>=41&& total<=67){
				totalMap.put("result",veryEdequate);
			}
		}
		scoreDetailMap.put(Constants.AHEMD_TYPE_ACTIVITY_SPACE,activitySpaceMap);
		scoreDetailMap.put(Constants.AHEMD_TYPE_ACTIVITY_DIVERSITY,activityDiversityMap);
		scoreDetailMap.put(Constants.AHEMD_TYPE_HEAVY_SPORT_TOYS,heavySportsToysMap);
		scoreDetailMap.put(Constants.AHEMD_TYPE_FINE_SPORT_TOYS,fineSportsToysMap);
		scoreMap.put("score", scoreDetailMap);

		//获取指导意见 使用app原来数据
		Map<String,Object> paramMap = new HashMap<>();
		List<String> moduleList = new ArrayList<String>();
		String activitySpaceId ="40288abe5167faf20151680235bd0002";
		String activityDiversityId ="40288abe5167faf201516802502e0003";
		String fineSportsToysId ="40288abe5167faf2015168026e890006";
		String heavySportsToysId ="40288abe5167faf2015168026e890004";
		moduleList.add(activitySpaceId);//活动空间
		moduleList.add(activityDiversityId);//活动多样性
		moduleList.add(fineSportsToysId);//精细运动玩具
		moduleList.add(heavySportsToysId);//粗大运动玩具

		paramMap.put("age",ageDay);//
		paramMap.put("questionModuleIds",moduleList);
		List<Map<String,Object>> guideList = followEvaluationDao.selectDefaultGuides(paramMap);
		List<PtEvaluationGuide> list = new ArrayList<PtEvaluationGuide>();
		if(!CollectionUtils.isEmpty(guideList)){
			Map<String,Object> temp = null;
			PtEvaluationGuide guide =null;
			double scoreMin = 0;
			double scoreMax = 0;
			for(int i =0;i<guideList.size();i++){
				temp = guideList.get(i);
				scoreMin = (double)temp.get("scoreMin");
				scoreMax = (double)temp.get("scoreMax");
				guide = new PtEvaluationGuide();
				guide.setCreateAuthor("admin");
				guide.setCreateTime(DateUtil.getSysDateA());
				guide.setId(SeqUtil.getSeqNo());
				guide.setRemark("根据得分结果生成指导");

				if(activitySpaceId.equals(temp.get("questionModuleId"))){
					if(activitySpace<=scoreMax && activitySpace>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.AHEMD_TYPE_ACTIVITY_SPACE);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}else if(activityDiversityId.equals(temp.get("questionModuleId"))){
					if(activityDiversity<=scoreMax && activityDiversity>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.AHEMD_TYPE_ACTIVITY_DIVERSITY);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}else if(heavySportsToysId.equals(temp.get("questionModuleId"))){
					if(heavySportsToys<=scoreMax && heavySportsToys>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.AHEMD_TYPE_HEAVY_SPORT_TOYS);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}else if(fineSportsToysId.equals(temp.get("questionModuleId"))){
					if(fineSportsToys<=scoreMax && fineSportsToys>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.AHEMD_TYPE_FINE_SPORT_TOYS);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}
			}
			scoreMap.put("guideList",list);
		}

		return scoreMap;
	}

	@Override
	//默认 所有题目必答
	public Map<String, Object> getAsqScore(Map<String, Object> map)
			throws Exception {
		String postions = (String)map.get("postionIds");
		Patient pt = (Patient)map.get("Patient");
		List<JSONObject> postionList = followEvaluationService.getPregnantCommonPostion(map);
		//传入答题 结果
		JSONObject jsonEsb = JSON.parseObject(postions);
		String well ="发育良好",low="低风险",littleHigh="风险略高",high="风险偏高";
		float communicate = 0, bigAction=0, fineAction=0, solveProblem=0, personSocial=0;
		//沟通 粗大动作 精细运动 解决问题 个人-社会
		Map<String,Object> communicateMap = new HashMap<String,Object>(),
				bigActionMap = new HashMap<String,Object>(),fineActionMap = new HashMap<String,Object>(),
				solveProblemMap = new HashMap<String,Object>(),personSocialMap = new HashMap<String,Object>();

		//后续修改跟 答题结果循环
		for(int i = 0 ;i<postionList.size();i++){
			String factor = postionList.get(i).getString("activity");
			String id = postionList.get(i).getString("id");
			String answerId = jsonEsb.getString(id);
			JSONArray answers =  postionList.get(i).getJSONArray("answer");
			if(null != answers && !StringUtils.isEmpty(answerId)){
				for(int j = 0 ;j<answers.size();j++){
					JSONObject obj = answers.getJSONObject(j);
					String idStr = obj.getString("id");
					if(answerId.equals(idStr)){
						int score = obj.getIntValue("score");
						if(Constants.ASQ_TYPE_COMMUNICATE.equals(factor)){
							communicate+=score;
							break;//单选题  匹配一项及退出答案匹配循环
						}else if(Constants.ASQ_TYPE_BIG_ACTION.equals(factor)){
							bigAction+=score;
							break;
						}else if(Constants.ASQ_TYPE_FINE_ACTION.equals(factor)){
							fineAction+=score;
							break;
						}else if(Constants.ASQ_TYPE_SOLVE_PROBLEM.equals(factor)){
							solveProblem+=score;
							break;
						}else if(Constants.ASQ_TYPE_PERSON_SOCIAL.equals(factor)){
							personSocial+=score;
							break;
						}
					}
				}
			}
		}

		Map<String, Object> scoreMap = new HashMap<String, Object>();

		communicateMap.put("score",communicate);
		communicateMap.put("desc","沟通");
		bigActionMap.put("score",bigAction);
		bigActionMap.put("desc","粗大动作");
		fineActionMap.put("score",fineAction);
		fineActionMap.put("desc"," 精细运动");
		solveProblemMap.put("score",solveProblem);
		solveProblemMap.put("desc","解决问题");
		personSocialMap.put("score",personSocial);
		personSocialMap.put("desc","个人-社会");

		Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
		long ageDay = (new Date().getTime()-birthLong)/(1000*60*60*24);
//		int ageMonth = ToolUtils.getAgeMonthByBirthday(DateUtil.getDate_8(new Date()),DateUtil.getDate_8(new Date(birthLong)));
		//如果客户端可以修改年龄  需要 app用户自己年龄 来判断  标准 后续放入redis
		String levelStr ="[{\"ageMax\":90,\"ageMin\":0,\"levels\":[[43.63,30.19,16.76],[50.62,41.63,32.63],[50.07,41.85,33.63],[45.9,33.41,20.92],[45.68,35.2,24.72]]},"
				+ "	{\"ageMax\":150,\"ageMin\":91,\"levels\":[[48.76,37.84,26.92],[48.94,37.26,25.59],[43.33,29.57,15.81],[47.76,35.84,23.91],[45.38,33.26,21.14]]},"
				+ "	{\"ageMax\":210,\"ageMin\":151,\"levels\":[[49.07,39.4,29.74],[34.76,19.99,5.22],[42.87,29.55,16.23],[42.32,27.21,12.09],[34.55,18.62,2.7]]},"
				+ "	{\"ageMax\":270,\"ageMin\":211,\"levels\":[[47.51,37.78,28.05],[39.89,25.73,11.57],[48.46,34.78,21.1],[50.08,38.65,27.21],[42.98,28.17,13.35]]},"
				+ "	{\"ageMax\":330,\"ageMin\":271,\"levels\":[[42.56,28.5,14.44],[32.72,16.84,0.97],[47.32,35.45,23.59],[47.1,35.93,24.77],[42.79,30.17,17.56]]},"
				+ "	{\"ageMax\":390,\"ageMin\":331,\"levels\":[[51.61,42.04,32.46],[45.16,30.43,15.69],[49.26,38.62,27.97],[46.42,34.56,22.7],[44.33,31.19,18.05]]},"
				+ "	{\"ageMax\":450,\"ageMin\":391,\"levels\":[[51.77,29.05,17.7],[65.965,43.086,20.207],[58.45,38.5102,18.5704],[57.615,37.6752,17.7354],[58.45,38.7106,18.9712]]},"
				+ "	{\"ageMax\":510,\"ageMin\":451,\"levels\":[[47.2944,28.0727,17.05905],[79.325,63.3097,47.2944],[70.14,53.4066,36.6732],[67.635,50.9517,34.2684],[60.12,44.1381,28.1562]]},"
				+ "	{\"ageMax\":570,\"ageMin\":511,\"levels\":[[49.599,21.8102,10.69468],[75.484,62.4246,49.3652],[80.995,57.3144,33.6338],[58.784,42.9858,27.1876],[61.79,45.4073,29.0246]]}]";

		Map<String, Map<String, Object>> scoreDetailMap = new HashMap<String,Map<String, Object>>();
		scoreDetailMap.put(Constants.ASQ_TYPE_COMMUNICATE,communicateMap);
		scoreDetailMap.put(Constants.ASQ_TYPE_BIG_ACTION,bigActionMap);
		scoreDetailMap.put(Constants.ASQ_TYPE_FINE_ACTION,fineActionMap);
		scoreDetailMap.put(Constants.ASQ_TYPE_SOLVE_PROBLEM,solveProblemMap);
		scoreDetailMap.put(Constants.ASQ_TYPE_PERSON_SOCIAL,personSocialMap);

		JSONArray arr = JSON.parseArray(levelStr);
		if(null != arr){
			for(int i = 0;i<arr.size();i++){
				int ageMin = arr.getJSONObject(i).getIntValue("ageMin");
				int ageMax = arr.getJSONObject(i).getIntValue("ageMax");
				JSONArray levels = null;
				if(ageDay>=ageMin&&ageDay<=ageMax){
					levels = arr.getJSONObject(i).getJSONArray("levels");
				}

				if(levels != null && levels.size()==5){
					//遍历map
					for (String key : scoreDetailMap.keySet()) {
						JSONArray moduleLevels =  null;
						if(Constants.ASQ_TYPE_COMMUNICATE.equals(key)){
							moduleLevels = levels.getJSONArray(0);
						}else if(Constants.ASQ_TYPE_BIG_ACTION.equals(key)){
							moduleLevels = levels.getJSONArray(0);
						}else if(Constants.ASQ_TYPE_FINE_ACTION.equals(key)){
							moduleLevels = levels.getJSONArray(0);
						}else if(Constants.ASQ_TYPE_SOLVE_PROBLEM.equals(key)){
							moduleLevels = levels.getJSONArray(0);
						}else if(Constants.ASQ_TYPE_PERSON_SOCIAL.equals(key)){
							moduleLevels = levels.getJSONArray(0);
						}
						float min = moduleLevels.getFloatValue(2);
						float aver = moduleLevels.getFloatValue(1);
						float max = moduleLevels.getFloatValue(0);
						float score = (float)scoreDetailMap.get(key).get("score");
						if(score>max){
							scoreDetailMap.get(key).put("result",well);
						}else if(score<=max && score>aver){
							scoreDetailMap.get(key).put("result",low);
						}else if(score<=aver && score>min){
							scoreDetailMap.get(key).put("result",littleHigh);
						}else if(score<=min){
							scoreDetailMap.get(key).put("result",high);
						}
					}
				}
			}
		}
		scoreMap.put("maxScore","60");
		scoreMap.put("score", scoreDetailMap);

		//获取指导意见 使用app原来数据
		Map<String,Object> paramMap = new HashMap<>();
		List<String> moduleList = new ArrayList<String>();
		String communicateId ="40288abe5167faf2015168029e7a0005";//沟通
		String bigActionId ="40288abe5167faf201516802c93a0006";//粗大动作
		String fineActionId ="40288abe5167faf20151680314a60007";//精细动作
		String solveProblemId ="40288abe5167faf201516803403e0008";//解决问题
		String personSocialId ="40288abe5167faf201516803864a0009";//个人-社会
		moduleList.add(communicateId);
		moduleList.add(bigActionId);
		moduleList.add(fineActionId);
		moduleList.add(solveProblemId);
		moduleList.add(personSocialId);

		paramMap.put("age",ageDay);//TODO
		paramMap.put("questionModuleIds",moduleList);
		List<Map<String,Object>> guideList = followEvaluationDao.selectDefaultGuides(paramMap);
		List<PtEvaluationGuide> list = new ArrayList<PtEvaluationGuide>();
		if(!CollectionUtils.isEmpty(guideList)){
			Map<String,Object> temp = null;
			PtEvaluationGuide guide =null;
			double scoreMin = 0;
			double scoreMax = 0;
			for(int i =0;i<guideList.size();i++){
				temp = guideList.get(i);
				scoreMin = (double)temp.get("scoreMin");
				scoreMax = (double)temp.get("scoreMax");
				guide = new PtEvaluationGuide();
				guide.setCreateAuthor("admin");
				guide.setCreateTime(DateUtil.getSysDateA());
				guide.setId(SeqUtil.getSeqNo());
				guide.setRemark("根据得分结果生成指导");

				if(communicateId.equals(temp.get("questionModuleId"))){
					if(communicate<=scoreMax && communicate>scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.ASQ_TYPE_COMMUNICATE);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}else if(bigActionId.equals(temp.get("questionModuleId"))){
					if(bigAction<scoreMax && bigAction>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.ASQ_TYPE_BIG_ACTION);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}else if(fineActionId.equals(temp.get("questionModuleId"))){
					if(fineAction<scoreMax && fineAction>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.ASQ_TYPE_FINE_ACTION);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}else if(solveProblemId.equals(temp.get("questionModuleId"))){
					if(solveProblem<scoreMax && solveProblem>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.ASQ_TYPE_SOLVE_PROBLEM);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}else if(personSocialId.equals(temp.get("questionModuleId"))){
					if(personSocial<scoreMax && personSocial>=scoreMin){
						guide.setGuide((String)temp.get("note"));
						guide.setModuleCode(Constants.ASQ_TYPE_PERSON_SOCIAL);
						guide.setSort((int)temp.get("sort"));
						list.add(guide);
					}
				}
			}
			scoreMap.put("guideList",list);
		}
		return scoreMap;
	}

	@Override
	public Map<String, Object> getPEABODYScore(Map<String, Object> mapIn) throws Exception {
		JSONObject jsonEsb = null;
		try {
			String postions = (String)mapIn.get("postionIds");
			jsonEsb = JSON.parseObject(postions);
		} catch (Exception e) {
			jsonEsb = (JSONObject) mapIn.get("postionIds");
		}
		// 传入答题 结果
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 小写的mm表示的是分钟
		boolean flag = false;// 是否早产.默认非早产儿
		Patient patient = (Patient) mapIn.get("patient");
		String birthday = patient.getBirthday();
		if (null == birthday) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_BIRTHDAY_NOT_EXIST, "用户没有出生日期");
		}
		Date date = new Date();
		String createTime = sdf.format(date);// 评估时间
		String expectedDay = patient.getExpectedDay();
		// 预产期，是否有预产期，如果没有默认是非早产儿
		// 如果有预产期，判断是否早产
		int mouth = 0;// 月数
		int day = 0;// 天数
		if (null != expectedDay) {
			// 比较两个时间的大小
			int bigOne = DateUtil.compare_date(birthday, expectedDay);

			Date date1 = sdf.parse(expectedDay);
			Date date2 = sdf.parse(birthday);
			Date date3 = sdf.parse(createTime);// 评估时间
			// 计算两个时间差(评估时用户年龄)
			int ages = DateUtil.daysBetween(date2, date3);
			int ageMouth = ages / 30;

			// 如果预产期大于出生日期，显示为早产,并计算出时间差
			if (bigOne < 0 && ageMouth < 24) {
				int expect = DateUtil.daysBetween(date2, date1);
				flag = true;
				mouth = expect / 30;
				day = expect % 30;
			}
		}

		// 计算月龄
		int day3 = 0;// 天
		int month3 = 0;// 月
		int year3 = 0;// 年
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("birthday", birthday);
		map.put("createTime", createTime);
		// 调用计算组件
		Map<String, Object> mapOut = ToolUtils.CalculateAgeOfMoon(map);
		if (mapOut != null && mapOut.size() > 0) {
			day3 = (int) mapOut.get("day3");
			month3 = (int) mapOut.get("month3");
			year3 = (int) mapOut.get("year3");
		}

		// 如果是早产儿，且年龄在24个月之内的儿童需要计算纠正年龄 flag=true 为早产儿
		// 用计算出来的月龄减去早产的时间获取纠正年龄
		if (flag) {
			if (day3 > day || day3 == day) {
				day3 = day3 - day;
			} else {
				if (month3 > mouth) {
					day3 = day3 + 30 - day;
					month3 = month3 - 1;
				} else {
					if (year3 > 0) {
						day3 = day3 + 30 - day;
						month3 = month3 + 12 - 1;
						year3 = year3 - 1;
					}
				}
			}
			if (month3 > mouth) {
				month3 = month3 - mouth;
			} else {
				if (year3 > 0) {
					month3 = month3 + 12 - mouth;
					year3 = year3 - 1;
				}
			}
		}
		// 计算最后的月龄
		int moon = year3 * 12 + month3;
		int days = year3 * 365 + month3 * 30 + day3;
		map.clear();// 清空信息
		map.put("moon", moon);
		map.put("days", days);
		map.put("Result", jsonEsb.getString("itemTotalScore"));
		Map<String, Object> MapOut = getAnswer(map);
		return MapOut;
	}

	private Map<String, Object> getAnswer(Map<String, Object> map) throws Exception {
		Map<String, Object> mapOutstr = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			int moon = (int) map.get("moon");
			int days = (int) map.get("days");
			logger.info(moon);
			logger.info(days);
			String result = (String) map.get("Result");
			int reflex = 0;// 反射
			int posture = 0;// 姿势
			int move = 0;// 移动
			int operation = 0;// 实物操作
			int grab = 0;// 抓握
			int vision = 0;// 视觉运动

			if (!StringUtils.isEmpty(result)) {
				JSONObject json = JSONObject.parseObject(result);
				if (!StringUtils.isEmpty(json.getString("reflex"))) {
					reflex = Integer.parseInt(json.getString("reflex"));
				}
				if (!StringUtils.isEmpty(json.getString("posture"))) {
					posture = Integer.parseInt(json.getString("posture"));
				}
				if (!StringUtils.isEmpty(json.getString("motion"))) {
					move = Integer.parseInt(json.getString("motion"));
				}
				if (!StringUtils.isEmpty(json.getString("practice"))) {
					operation = Integer.parseInt(json.getString("practice"));
				}
				if (!StringUtils.isEmpty(json.getString("grab"))) {
					grab = Integer.parseInt(json.getString("grab"));
				}
				if (!StringUtils.isEmpty(json.getString("visuomotor"))) {
					vision = Integer.parseInt(json.getString("visuomotor"));
				}
			}
			logger.info(reflex + "  " + posture + "  " + move + "  " + operation + "  " + grab + "  " + vision);
			String answerId = Constants.FOLLOW_EVALUATION_PEABODY_ANSWER_ALL;
			String reflexstr = "";// 反射
			String posturestr = "";// 姿势
			String movestr = "";// 移动
			String grabstr = "";// 抓握
			String visionstr = "";// 视觉运动
			String operationstr = "";// 实物操作

			// 获取相当年龄
			String json3 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
					Constants.FOLLOW_EVALUATION_PEABODY_ANSWER_AGE);
			if (StringUtils.isEmpty(json3)) {
				paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key", Constants.FOLLOW_EVALUATION_PEABODY_ANSWER_AGE);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if (null != position) {
					json3 = position.getValue();
					 jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PEABODY_ANSWER_AGE, json3);

				}
			}

			net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(json3); // 首先把字符串转成 JSONArray 对象
			if (jsonArray.size() > 0) {
				for (int i = 0; i < jsonArray.size(); i++) {
					net.sf.json.JSONObject job = jsonArray.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
					reflexstr = (String) job.get("reflex");
					posturestr = (String) job.get("posture");
					movestr = (String) job.get("move");
					grabstr = (String) job.get("grab");
					visionstr = (String) job.get("vision");
					operationstr = (String) job.get("practice");
					Map<String, Object> maResult1 = null;
					if (moon < 12) {
						maResult1 = mateAnswer(reflexstr, "reflex", reflex, job, "ConsiderableAge", "");
					} else {
						maResult1 = mateAnswer(operationstr, "operation", operation, job, "ConsiderableAge", "");
					}
					Map<String, Object> maResult2 = mateAnswer(posturestr, "posture", posture, job, "ConsiderableAge",
							"");
					Map<String, Object> maResult3 = mateAnswer(movestr, "move", move, job, "ConsiderableAge", "");
					Map<String, Object> maResult5 = mateAnswer(grabstr, "grab", grab, job, "ConsiderableAge", "");
					Map<String, Object> maResult6 = mateAnswer(visionstr, "vision", vision, job, "ConsiderableAge", "");
					if (maResult1 != null && maResult1.size() > 0) {
						mapOutstr.putAll(maResult1);
					}
					if (maResult2 != null && maResult2.size() > 0) {
						mapOutstr.putAll(maResult2);
					}
					if (maResult3 != null && maResult3.size() > 0) {
						mapOutstr.putAll(maResult3);
					}
					if (maResult5 != null && maResult5.size() > 0) {
						mapOutstr.putAll(maResult5);
					}
					if (maResult6 != null && maResult6.size() > 0) {
						mapOutstr.putAll(maResult6);
					}
				}
			}

			if (days < 30) {
				// 获取评分标准
				answerId = answerId + "1";
				String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY, answerId);
				if (StringUtils.isEmpty(json)) {
					paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
					paramMap.put("key", answerId);
					FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
					if (null != position) {
						json = position.getValue();
						jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,answerId, json);

					}
				}
				jsonArray = net.sf.json.JSONArray.fromObject(json); // 首先把字符串转成 JSONArray 对象
				if (jsonArray.size() > 0) {
					for (int i = 0; i < jsonArray.size(); i++) {
						net.sf.json.JSONObject job = jsonArray.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
						reflexstr = (String) job.get("reflex");
						posturestr = (String) job.get("posture");
						movestr = (String) job.get("move");
						grabstr = (String) job.get("grab");
						visionstr = (String) job.get("vision");
						Map<String, Object> maResult1 = mateAnswer(reflexstr, "reflex", reflex, job, "Standard",
								"percentile");
						Map<String, Object> maResult2 = mateAnswer(posturestr, "posture", posture, job, "Standard",
								"percentile");
						Map<String, Object> maResult3 = mateAnswer(movestr, "move", move, job, "Standard",
								"percentile");
						Map<String, Object> maResult5 = mateAnswer(grabstr, "grab", grab, job, "Standard",
								"percentile");
						Map<String, Object> maResult6 = mateAnswer(visionstr, "vision", vision, job, "Standard",
								"percentile");
						if (maResult1 != null && maResult1.size() > 0) {
							mapOutstr.putAll(maResult1);
						}
						if (maResult2 != null && maResult2.size() > 0) {
							mapOutstr.putAll(maResult2);
						}
						if (maResult3 != null && maResult3.size() > 0) {
							mapOutstr.putAll(maResult3);
						}
						if (maResult5 != null && maResult5.size() > 0) {
							mapOutstr.putAll(maResult5);
						}
						if (maResult6 != null && maResult6.size() > 0) {
							mapOutstr.putAll(maResult6);
						}
					}
				}
			} else {
				Map<String, Object> mapInfo = new HashMap<String, Object>();
				mapInfo.put("id", "88");
				Map<String, Object> mapOut1 = new HashMap<String, Object>();
				mapOut1 = patientdao.selectoutTableInfo(mapInfo);
				String[] arrystr = null;
				if (!CollectionUtils.isEmpty(mapOut1)) {
					// 获取评分标准
					String json1 = mapOut1.get("template").toString();
					net.sf.json.JSONObject node1 = net.sf.json.JSONObject.fromObject(json1);
					String strid = "";
					Iterator<?> it = node1.keys();
					while (it.hasNext()) {
						String key = it.next().toString();
						if (key.indexOf("~") == -1) {
							if (key.equals("" + moon)) {
								strid = node1.getString(key);
								break;
							}
						} else {
							arrystr = key.split("~");
							if (moon >= Integer.parseInt(arrystr[0]) && moon <= Integer.parseInt(arrystr[1])) {
								strid = node1.getString(key);
								break;
							}
						}
					}
					answerId = answerId + strid;
					logger.info("answerId : " + answerId);
					String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY, answerId);
					if (StringUtils.isEmpty(json)) {
						paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
						paramMap.put("key", answerId);
						FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
						if (null != position) {
							json = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,answerId, json);

						}
					}
					jsonArray = net.sf.json.JSONArray.fromObject(json); // 首先把字符串转成 JSONArray 对象
					if (jsonArray.size() > 0) {
						for (int i = 0; i < jsonArray.size(); i++) {
							net.sf.json.JSONObject job = jsonArray.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
							reflexstr = (String) job.get("reflex");
							posturestr = (String) job.get("posture");
							movestr = (String) job.get("move");
							grabstr = (String) job.get("grab");
							visionstr = (String) job.get("vision");
//							operationstr = (String) job.get("operation");
							operationstr = (String) job.get("practice");
							Map<String, Object> maResult1 = null;
							if (moon < 12) {
								maResult1 = mateAnswer(reflexstr, "reflex", reflex, job, "Standard", "percentile");
							} else {
								maResult1 = mateAnswer(operationstr, "operation", operation, job, "Standard", "percentile");
							}
							Map<String, Object> maResult2 = mateAnswer(posturestr, "posture", posture, job, "Standard",
									"percentile");
							Map<String, Object> maResult3 = mateAnswer(movestr, "move", move, job, "Standard",
									"percentile");
							Map<String, Object> maResult5 = mateAnswer(grabstr, "grab", grab, job, "Standard",
									"percentile");
							Map<String, Object> maResult6 = mateAnswer(visionstr, "vision", vision, job, "Standard",
									"percentile");
							if (maResult1 != null && maResult1.size() > 0) {
								mapOutstr.putAll(maResult1);
							}
							if (maResult2 != null && maResult2.size() > 0) {
								mapOutstr.putAll(maResult2);
							}
							if (maResult3 != null && maResult3.size() > 0) {
								mapOutstr.putAll(maResult3);
							}
							if (maResult5 != null && maResult5.size() > 0) {
								mapOutstr.putAll(maResult5);
							}
							if (maResult6 != null && maResult6.size() > 0) {
								mapOutstr.putAll(maResult6);
							}
						}
					}
				}

			}
			logger.info("mapOutstr:" + mapOutstr.toString());
			if (mapOutstr != null && mapOutstr.size() > 0) {
				reflex = 0;
				operation = 0;
				posture = 0;
				move = 0;
				grab = 0;
				vision = 0;// 初始化
				for (int i = 0; i < mapOutstr.size(); i++) {
						if (moon < 12) {
							if (!StringUtils.isEmpty((String) mapOutstr.get("reflexStandard"))){
							reflex = Integer.parseInt((String) mapOutstr.get("reflexStandard"));
							}
						} else {
							if (!StringUtils.isEmpty((String) mapOutstr.get("operationStandard"))) {
								operation = Integer.parseInt((String) mapOutstr.get("operationStandard"));
						}
					}
					if (!StringUtils.isEmpty((String) mapOutstr.get("postureStandard"))) {
						posture = Integer.parseInt((String) mapOutstr.get("postureStandard"));
					}
					if (!StringUtils.isEmpty((String) mapOutstr.get("moveStandard"))) {
						move = Integer.parseInt((String) mapOutstr.get("moveStandard"));
					}
					if (!StringUtils.isEmpty((String) mapOutstr.get("grabStandard"))) {
						grab = Integer.parseInt((String) mapOutstr.get("grabStandard"));
					}
					if (!StringUtils.isEmpty((String) mapOutstr.get("visionStandard"))) {
						vision = Integer.parseInt((String) mapOutstr.get("visionStandard"));
					}
				}
			}
			int fineMotor = grab + vision; // 精细运动
			int CrossMotor = reflex + posture + move + operation; // 粗大运动
			int TotalMovement = reflex + posture + move + operation + grab + vision;// 总
			logger.info(reflex + "  " + posture + "  " + move + "  " + operation + "  " + grab + "  " + vision);

			mapOutstr.put("fineMotor", fineMotor);
			mapOutstr.put("CrossMotor", CrossMotor);
			mapOutstr.put("TotalMovement", TotalMovement);
			logger.info(fineMotor + "  " + CrossMotor + "  " + TotalMovement);

			// 获取商
			String json2 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
					Constants.FOLLOW_EVALUATION_PEABODY_ANSWER_DISCUSS);
			if (StringUtils.isEmpty(json2)) {
				paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key", Constants.FOLLOW_EVALUATION_PEABODY_ANSWER_DISCUSS);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if (null != position) {
					json2 = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PEABODY_ANSWER_DISCUSS, json2);
				}
			}

			String Movement = "";
			String Cross = "";
			String fine = "";
			jsonArray = net.sf.json.JSONArray.fromObject(json2); // 首先把字符串转成 JSONArray 对象
			if (jsonArray.size() > 0) {
				for (int i = 0; i < jsonArray.size(); i++) {
					net.sf.json.JSONObject job = jsonArray.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
					Movement = (String) job.get("TotalMovement");
					Cross = (String) job.get("CrossMotor");
					fine = (String) job.get("fineMotor");
					Map<String, Object> maResult1 = mateAnswer(Movement, "TotalMovement", TotalMovement, job, "discuss",
							"percentile");
					Map<String, Object> maResult2 = mateAnswer(Cross, "CrossMotor", CrossMotor, job, "discuss",
							"percentile");
					Map<String, Object> maResult3 = mateAnswer(fine, "fineMotor", fineMotor, job, "discuss",
							"percentile");
					if (maResult1 != null && maResult1.size() > 0) {
						mapOutstr.putAll(maResult1);
					}
					if (maResult2 != null && maResult2.size() > 0) {
						mapOutstr.putAll(maResult2);
					}
					if (maResult3 != null && maResult3.size() > 0) {
						mapOutstr.putAll(maResult3);
					}
				}
			}
			logger.info("mapOutstr1111:" + mapOutstr.toString());

			logger.info(mapOutstr.toString());
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
							"Redis缓存关闭失败!"));
				}
			}
		}
		return mapOutstr;
	}

	// 匹配信息
	private Map<String, Object> mateAnswer(String str, String type, int reflex, net.sf.json.JSONObject job,
			String Standard, String percentile) throws Exception {
		// logger.info(str+" "+type+" "+reflex+" "+Standard+" "+percentile);
		// logger.info(job);
		String[] arry = null;
		Map<String, Object> mapOutstr = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(str)) {
			if (str.indexOf("<") == -1) {
				if (str.indexOf(">") == -1) {
					if (str.indexOf("~") == -1) {
						if (str.equals(reflex + "") && reflex != 0) {
							if (StringUtils.isEmpty(percentile)) {
								mapOutstr.put(type + Standard, job.get(Standard));
							} else {
								mapOutstr.put(type + Standard, job.get(Standard));
								mapOutstr.put(type + percentile, job.get(percentile));
							}
							// flag = true;
						}
					} else {
						arry = str.split("~");
						if (reflex >= Integer.parseInt(arry[0]) && reflex <= Integer.parseInt(arry[1]) && reflex != 0) {
							if (StringUtils.isEmpty(percentile)) {
								mapOutstr.put(type + Standard, job.get(Standard));
							} else {
								mapOutstr.put(type + Standard, job.get(Standard));
								mapOutstr.put(type + percentile, job.get(percentile));
							}
							// flag = true;
						}
					}
				} else {
					arry = str.split(">");
					if (reflex > Integer.parseInt(arry[1]) && reflex != 0) {
						if (StringUtils.isEmpty(percentile)) {
							mapOutstr.put(type + Standard, job.get(Standard));
						} else {
							mapOutstr.put(type + Standard, job.get(Standard));
							mapOutstr.put(type + percentile, job.get(percentile));
						}
						// flag = true;
					}
				}
			} else {
				arry = str.split("<");
				if (reflex < Integer.parseInt(arry[1]) && reflex != 0) {
					if (StringUtils.isEmpty(percentile)) {
						mapOutstr.put(type + Standard, job.get(Standard));
					} else {
						logger.info("str" + str);
						logger.info(job);
						mapOutstr.put(type + Standard, job.get(Standard));
						mapOutstr.put(type + percentile, job.get(percentile));
					}
					// flag = true;
				}
			}
		}
		return mapOutstr;
	}

	@Override
	public Map<String, Object> getBSID2Score(Map<String, Object> mapIn,String Type) throws Exception {
		JSONObject jsonEsb = null;
		try {
			String postions = (String) mapIn.get("postionIds");
			jsonEsb = JSON.parseObject(postions);
		} catch (Exception e) {
			jsonEsb = (JSONObject) mapIn.get("postionIds");
		}
		// 传入答题 结果
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 小写的mm表示的是分钟
		boolean flag = false;// 是否早产.默认非早产儿
		Patient patient = (Patient) mapIn.get("patient");
		String birthday = patient.getBirthday();
		if (null == birthday) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_BIRTHDAY_NOT_EXIST, "用户没有出生日期");
		}
		Date date = new Date();
		String createTime = sdf.format(date);// 评估时间
		String expectedDay = patient.getExpectedDay();
		// 预产期，是否有预产期，如果没有默认是非早产儿
		// 如果有预产期，判断是否早产
		int mouth = 0;// 月数
		int day = 0;// 天数
		if (null != expectedDay) {
			// 比较两个时间的大小
			int bigOne = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
			Date date1 = sdf.parse(expectedDay);
			Date date2 = sdf.parse(birthday);
			Date date3 = sdf.parse(createTime);// 评估时间
			// 计算两个时间差(评估时用户年龄)
			int ages = DateUtil.daysBetween(date2, date3);
			int ageMouth = ages / 30;

			// 如果预产期大于出生日期 孕周小于37周，显示为早产,并计算出时间差
			if (bigOne < 260 && ageMouth < 31) {
				int expect = DateUtil.daysBetween(date2, date1);
				flag = true;
				mouth = expect / 30;
				day = expect % 30;
			}
		}
		// 计算月龄
		int day3 = 0;// 天
		int month3 = 0;// 月
		int year3 = 0;// 年
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("birthday", birthday);
		map.put("createTime", createTime);
		// 调用计算组件
		Map<String, Object> mapOut = ToolUtils.CalculateAgeOfMoon(map);
		if (mapOut != null && mapOut.size() > 0) {
			day3 = (int) mapOut.get("day3");
			month3 = (int) mapOut.get("month3");
			year3 = (int) mapOut.get("year3");
		}
		// 如果是早产儿，且年龄在24个月之内的儿童需要计算纠正年龄 flag=true 为早产儿
		// 用计算出来的月龄减去早产的时间获取纠正年龄
		if (flag) {
			if (day3 > day || day3 == day) {
				day3 = day3 - day;
			} else {
				if (month3 > mouth) {
					day3 = day3 + 30 - day;
					month3 = month3 - 1;
				} else {
					if (year3 > 0) {
						day3 = day3 + 30 - day;
						month3 = month3 + 12 - 1;
						year3 = year3 - 1;
					}
				}
			}
			if (month3 > mouth) {
				month3 = month3 - mouth;
			} else {
				if (year3 > 0) {
					month3 = month3 + 12 - mouth;
					year3 = year3 - 1;
				}
			}
		}
		// 计算最后的月龄
		int days = year3 * 365 + month3 * 30 + day3;
		DecimalFormat df = new DecimalFormat("0.0");//格式化小数
	    String moonStr = df.format((float)days/30);//返回的是String类型
		double moon = Double.parseDouble(moonStr);
		//判断年龄是否在2~30月之间
		map.clear();// 清空信息
		map.put("moon", moon);
		map.put("days", days);
		map.put("Result", jsonEsb.getString("score"));
		Map<String, Object> MapOut = new HashMap<String,Object>();
		if (Constants.FOLLOW_EVALUATION_PREGNANT_BSID.equals(Type)) {
			if(days<16 || days>1275) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "贝利3支持年龄为16天到42个月15天的宝宝"));
			}
			MapOut = getBSIDAnswer(map);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID2.equals(Type)) {
			if(moon<2 || moon>30) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "贝利2支持月龄2~30月龄!"));
			}
			MapOut = getBSID2Answer(map);
		}
		return MapOut;

	}

	//贝利3
	private Map<String, Object> getBSIDAnswer(Map<String, Object> map) throws Exception{
		logger.info(" getBSIDAnswer :    "+map.toString());
		Map<String, Object> mapOutstr = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			//月龄
			double moon  = (double) map.get("moon");
			int  days =(int)map.get("days");; //宝宝年龄（天）
			int moonInt =(int)moon; //需要转成整型，用来查询评分表
			String result = (String) map.get("Result");
			//判断是否有值
			if(!StringUtils.isEmpty(result)) {
				/**原始分获取*/
				JSONObject json = JSONObject.parseObject(result);
				//获取认知原始分
				String cogScore = json.getString("cogScore");
				//获取接受性交流原始分
				String RCSocre = json.getString("RCSocre");
				//获取表达性交流原始分
				String ECSocre = json.getString("ECSocre");
				//获取精细运动原始分
				String FMSocre = json.getString("FMSocre");
				//获取大运动原始分
				String GMSocre = json.getString("GMSocre");

				/**评分表获取*/
				//接受性交流
				String json1 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_PREGNANT_BSID_RC);
				 //表达性交流
				String json2 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_PREGNANT_BSID_EC);
				//精细运动
				String json3 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_PREGNANT_BSID_FM);
				//大运动
				String json4 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_PREGNANT_BSID_GM);
				//认知
				String json5 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_PREGNANT_BSID_COG);
				//发育商和发育龄
				String json6 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_PREGNANT_BSID_MIX);

				//如果在redis中无法查询到，则通过数据库查询，然后放入redis缓存中
				if (StringUtils.isEmpty(json1) ||StringUtils.isEmpty(json2)||StringUtils.isEmpty(json3)||StringUtils.isEmpty(json4)||StringUtils.isEmpty(json5)||StringUtils.isEmpty(json6)) {
					paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
					paramMap.put("type", Constants.FOLLOW_EVALUATION_PREGNANT_BSIDANSWER);
					List<FuAssessMentPosition> positions = followEvaluationDao.selectAssessMentPositionBytype(paramMap);
					if(null != positions){
						for(int i =0;i<positions.size();i++) {
							FuAssessMentPosition position =  positions.get(i);
							if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID_RC.equals(position.getKey())) {
								json1 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID_RC,json1);
							}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID_EC.equals(position.getKey())) {
								json2 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID_EC,json2);
							}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID_FM.equals(position.getKey())) {
								json3 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID_FM,json3);
							}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID_GM.equals(position.getKey())) {
								json4 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID_GM,json4);
							}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID_COG.equals(position.getKey())) {
								json5 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID_COG,json5);
							}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID_MIX.equals(position.getKey())) {
								json6 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID_MIX,json6);
							}
						}
					}
				}
				//匹配信息
				Map<String,Object> MapIn = new HashMap<String,Object>();
				MapIn.put("cogScore", cogScore);
				MapIn.put("RCSocre", RCSocre);
				MapIn.put("ECSocre", ECSocre);
				MapIn.put("FMSocre", FMSocre);
				MapIn.put("GMSocre", GMSocre);
				MapIn.put("bsidRc", json1);
				MapIn.put("bsidEc", json2);
				MapIn.put("bsidFm", json3);
				MapIn.put("bsidGm", json4);
				MapIn.put("bsidCog", json5);
				MapIn.put("bsidMix", json6);
				MapIn.put("moonInt", moonInt);
				MapIn.put("moonDouble", moon);
				MapIn.put("days", days);
				//分数，商，年龄等匹配
				mapOutstr = matchAnswer3(MapIn);
				if(mapOutstr!=null) {
					mapOutstr.put("cogScore", cogScore);
					mapOutstr.put("RCSocre", RCSocre);
					mapOutstr.put("ECSocre", ECSocre);
					mapOutstr.put("FMSocre", FMSocre);
					mapOutstr.put("GMSocre", GMSocre);
				}
			}

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
							"Redis缓存关闭失败!"));
				}
			}
		}
		return mapOutstr;
	}

	//贝利2
	private Map<String, Object> getBSID2Answer(Map<String, Object> map) throws Exception {
		logger.info(" 贝利2 : "+map.toString());
		Map<String, Object> mapOutstr = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			//月龄
			double moon  = (double) map.get("moon");
			int moonInt =(int)moon; //需要转成整型，用来查询评分表
			String result = (String) map.get("Result");
			//判断是否有值
			if(!StringUtils.isEmpty(result)) {
				JSONObject json = JSONObject.parseObject(result);
				//获取智力原始分
				String mrSocre = json.getString("mrScore");
				//获取运动原始分
				String prSocre = json.getString("prScore");
				// 获取运动评分表
				String json1 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PR);
				// 获取智力评分表
				String json2 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_BSID2_ANSWER_MR);
				// 获取发育登记评分表
				String json3 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_BSID2_ANSWER_LEVEL);
				// 百分位
				String json4 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PERCENT);

				//如果在redis中无法查询到，则通过数据库查询，然后放入redis缓存中
				if (StringUtils.isEmpty(json1) ||StringUtils.isEmpty(json2)||StringUtils.isEmpty(json3)||StringUtils.isEmpty(json4)) {
					paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
					paramMap.put("type", Constants.FOLLOW_EVALUATION_PREGNANT_BSID2ANSWER);
					List<FuAssessMentPosition> positions = followEvaluationDao.selectAssessMentPositionBytype(paramMap);
					if(null != positions){
						for(int i =0;i<positions.size();i++) {
							FuAssessMentPosition position =  positions.get(i);
							if(Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PR.equals(position.getKey())) {
								json1 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PR,json1);
							}else if(Constants.FOLLOW_EVALUATION_BSID2_ANSWER_MR.equals(position.getKey())) {
								json2 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_BSID2_ANSWER_MR,json2);
							}else if(Constants.FOLLOW_EVALUATION_BSID2_ANSWER_LEVEL.equals(position.getKey())) {
								json3 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_BSID2_ANSWER_LEVEL,json3);
							}else if(Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PERCENT.equals(position.getKey())) {
								json4 = position.getValue();
								jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PERCENT,json4);
							}
						}
					}
				}
				//匹配信息
				Map<String,Object> MapIn = new HashMap<String,Object>();
				MapIn.put("json", json1);
				MapIn.put("level", json3);
				MapIn.put("percent", json4);
				MapIn.put("Socre", prSocre);
				MapIn.put("moonInt", moonInt);
				MapIn.put("moonDouble", moon);
				//运动
				Map<String,Object> mapPR = matchAnswer(MapIn,Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PR);
				MapIn.put("json", json2);
				MapIn.put("Socre", mrSocre);
				//智力
				Map<String,Object> mapMR = matchAnswer(MapIn,Constants.FOLLOW_EVALUATION_BSID2_ANSWER_MR);
				int mr = 0;
				int pr = 0;
				if(StringUtils.isEmpty(mapMR.get("mdiOrpdi"))) {
					if("高于150".equals(mapMR.get("mdiOrpdi"))) {
						mr = 150;
					}else if("低于50".equals(mapMR.get("mdiOrpdi"))) {
						mr = 50;
					}else {
						mr = Integer.parseInt((String) mapMR.get("mdiOrpdi"));
					}
				}

				if(StringUtils.isEmpty(mapPR.get("mdiOrpdi"))) {
					if("高于150".equals(mapPR.get("mdiOrpdi"))) {
						pr = 150;
					}else if("低于50".equals(mapPR.get("mdiOrpdi"))) {
						pr = 50;
					}else {
						pr = Integer.parseInt((String) mapPR.get("mdiOrpdi"));
					}
				}

				int poor = mr - pr;
				if(poor<17) {
					mapOutstr.put("difference", "无差异");
				}else if(poor>=17 && poor<=20) {
					mapOutstr.put("difference", "显著性差异");
				}else {
					mapOutstr.put("difference", "重要性差异");
				}

				mapMR.put("mrSocre", mrSocre);
				mapOutstr.put("MR", mapMR);
				mapPR.put("prSocre", prSocre);
				mapOutstr.put("PR", mapPR);
			}

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
							"Redis缓存关闭失败!"));
				}
			}
		}
		return mapOutstr;
	}

	//贝利2数据匹配
	@SuppressWarnings("unchecked")
	private Map<String,Object> matchAnswer (Map<String,Object> map , String type) {
		Map <String,Object> mapOut = new HashMap<String,Object>();
		String json = (String) map.get("json");//标准分对照表
		String level = (String) map.get("level");//发育等级表格
		String percent = (String) map.get("percent");//百分位表格
		int moonInt = (int) map.get("moonInt");//月龄
		double moon = (double) map.get("moonDouble");//月龄
		String Socre = (String) map.get("Socre");//基础分
		String mdiOrpdi = "";//（标准）粗分
		String[] arry = null;
		//匹配智力标准分、年龄和百分位
		//匹配运动标准分、年龄和百分位
		if(!StringUtils.isEmpty(Socre)) {
			int SocreInt = Integer.parseInt(Socre);
			net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(json); // 首先把字符串转成 json对象
			net.sf.json.JSONArray mrStr = (net.sf.json.JSONArray) jsonObject.get((moonInt+""));
			net.sf.json.JSONArray jsonArray = null;
			//获取当前时间
			List <Map<String,Object>> listJson = new ArrayList<Map<String,Object>>();
			Map<String,Object> mapIn = new HashMap<String,Object>();
			if(mrStr!=null) {
				 jsonArray = net.sf.json.JSONArray.fromObject(mrStr); // 首先把字符串转成 JSONArray 对象
				 //匹配标准分
				 for(int i=0; i<jsonArray.size();i++) {
					 net.sf.json.JSONObject json5 = (net.sf.json.JSONObject) jsonArray.get(i);
					 //判断是否包含当前值
					 if(json5.containsValue(Socre)) {
						 listJson.add((Map<String,Object>)json5);
					 }
					 //获取最大值和最小值
					 if(i==0) {
						//最大值
						 mapIn.put("maxJson", jsonArray.get(0));
					 }
					 if(i==jsonArray.size()-1) {
						 //最小值
						 mapIn.put("minJson", jsonArray.get(jsonArray.size()-1));
					 }

				 }
			}
			//如果没有匹配到标准分，怎和当前月龄对应的最大值和最小值比较
			if(listJson==null||listJson.size()<=0) {
			//获取最大和最小值，用于后期在标准分表中匹配不到时进行判断
			//1：大于表中测试分最大值则标准分显示 大于150 或者 >150
			//2：小于表中测试分最小值则标准分显示 小于50 或者 <50
			int max = 0;//最大标准分
			int min = 0;//最小标准分
			org.json.JSONObject maxJson = new org.json.JSONObject(mapIn.get("maxJson").toString());
			org.json.JSONObject minJson = new org.json.JSONObject(mapIn.get("minJson").toString());
			max  = Integer.parseInt(maxJson.getString("150"));
			min  = Integer.parseInt(minJson.getString("50"));
         	if(SocreInt>max) {
         		mdiOrpdi = "高于150";
			}else if(SocreInt<min) {
				mdiOrpdi = "低于50";
			}

			}else {
			//有值，因为一个基础分会对应多个标准分,需要需要对年龄进行分解
			//如：月龄为2.2（2~2.9都是二月龄），基础分为56，对应的标准分为 100,101,102三个，处理逻辑如下：
			//用 0.9/3 分成3份（2.3,2.6,2.9），判断月龄所在区间，2<2.2<2.3在此区间中，对应规则是相同基础分中月龄越小对应的标准分越大
			//则上述例子的标准分为102
				int length = listJson.size();
				int length1 = 1;
				String moonStr = new DecimalFormat("0.0").format((float)0.9/length);
				double basic = Double.parseDouble(moonStr);//基本分
				double average  = 0.0;
				double average1  = 0.0;
				int last = 0;//最后的值
				for(int i =0;i<length;i++) {
					average  = basic*(i)+moonInt;
					average1  = basic*(i+1)+moonInt;
					if(moon>=average && moon<average1) {
						last = i ;
						break;
					}else if(i == length-1 ) {
						last = i ;
					}
					length1 = length1 -1;
				}
				org.json.JSONObject finalJson = new org.json.JSONObject(listJson.get(last));
				Iterator<?> iterator = finalJson.keys();
	            while(iterator.hasNext()){
	                    String key = (String) iterator.next();
	                    mdiOrpdi = key;
	            }
			}
			mapOut.put("mdiOrpdi", mdiOrpdi);
			//匹配智龄
			int mdiOrpdiInt = 0;
			if(mdiOrpdi.indexOf("于")==-1 && !"".equals(mdiOrpdi)) {
				//转换粗分用于后期比较
				mdiOrpdiInt = Integer.parseInt(mdiOrpdi);
			}

			String intelligenceAge = "";
			net.sf.json.JSONObject jsonObject1 = net.sf.json.JSONObject.fromObject(level); // 首先把字符串转成 json对象
			net.sf.json.JSONArray mouth =  null;
			if(Constants.FOLLOW_EVALUATION_BSID2_ANSWER_PR.equals(type)) {
				mouth = (net.sf.json.JSONArray) jsonObject1.get("PRage");
				if(SocreInt<11) {
					intelligenceAge = "<2月";
				}else if(SocreInt>70) {
					intelligenceAge = ">30月";
				}
			}
			if(Constants.FOLLOW_EVALUATION_BSID2_ANSWER_MR.equals(type)) {
				mouth = (net.sf.json.JSONArray) jsonObject1.get("MRage");
				if(SocreInt<26) {
					intelligenceAge = "<2月";
				}else if(SocreInt>156) {
					intelligenceAge = ">30月";
				}
			}
			//如果不满足两端的条件进行匹配
			net.sf.json.JSONObject finalBegin= null;
			net.sf.json.JSONObject finalEnd= null;
			int bigvalue = 0;
			int smallVale = 0;
			if(StringUtils.isEmpty(intelligenceAge)) {
				for(int i = 0;i<mouth.size()-1;i++) {
					finalBegin = (net.sf.json.JSONObject) mouth.get(i);
					finalEnd = (net.sf.json.JSONObject) mouth.get(i+1);
					smallVale = Integer.parseInt((String) finalBegin.get("value"));
					bigvalue = Integer.parseInt((String) finalEnd.get("value"));
					if(SocreInt>=smallVale && SocreInt< bigvalue ) {
						intelligenceAge = 	(String) finalBegin.get("age");
					}else if(SocreInt == bigvalue){
						intelligenceAge = 	(String) finalEnd.get("age");
					}
				}
			}

			mapOut.put("intelligenceAge", intelligenceAge);

			//匹配发育等级
			net.sf.json.JSONArray Levels = (net.sf.json.JSONArray) jsonObject1.get("Level");
			if("高于150".equals(mdiOrpdi)) {
				mapOut.put("developmentGrade", "非常优秀");
			}else if("低于50".equals(mdiOrpdi)) {
				mapOut.put("developmentGrade", "发育迟滞");
			}else {
				net.sf.json.JSONObject finalJson= null;
				for(int i = 0;i<Levels.size();i++) {
					finalJson = (net.sf.json.JSONObject)Levels.get(i);
					Iterator<?> iterator = finalJson.keys();
		            while(iterator.hasNext()){
		                    String key = (String) iterator.next();
		                    if(key.indexOf("~")==-1) {
		                    	if(key.indexOf("130")==-1) {
		                    		if(key.indexOf("69")==-1) {
			                    	}else {
			                    		if(mdiOrpdiInt<=69) {
			                    			mapOut.put("developmentGrade", (String)finalJson.get(key));
			                    		}
			                    	}
		                    	}else {
		                    		if(mdiOrpdiInt>=130) {
		                    			mapOut.put("developmentGrade", (String)finalJson.get(key));
		                    		}
		                    	}
		                    }else {
		                    	arry = key.split("~");
								if (mdiOrpdiInt >= Integer.parseInt(arry[0]) && mdiOrpdiInt <= Integer.parseInt(arry[1]) && !"".equals(mdiOrpdi)) {
									mapOut.put("developmentGrade", (String)finalJson.get(key));
								}
		                    }

		            }
				}
			}

			//匹配百分位
			net.sf.json.JSONArray jsonObject2 = net.sf.json.JSONArray.fromObject(percent); // 首先把字符串转成 json对象
			if("高于150".equals(mdiOrpdi)) {
				mapOut.put("percent", ">99.90%");
			}else if("低于50".equals(mdiOrpdi)) {
				mapOut.put("percent", "<0.1%");
			}else {
				net.sf.json.JSONObject finalJson= null;
				for(int i = 0;i<jsonObject2.size();i++) {
					finalJson = (net.sf.json.JSONObject)jsonObject2.get(i);
					if(mdiOrpdi.equals(finalJson.get("score"))) {
						mapOut.put("percent", finalJson.get("percent"));
						mapOut.put("Ztype", finalJson.get("Ztype"));
					}
				}
			}
		}

		return mapOut;

	}

	//贝利3数据匹配
	private Map<String,Object> matchAnswer3 (Map<String,Object> map) {
		logger.info("matchAnswer3  : "+map.toString());
		Map<String,Object> mapOut = new  LinkedHashMap<String,Object>();
		int days = (int) map.get("days");
		//判断分数如果没有或者为空那么直接赋值为0
		String cogStandard  = toolsUtils(map.get("cogScore"),map.get("bsidCog"),days);//认知里表分
		String RCStandard  = toolsUtils(map.get("RCSocre"),map.get("bsidRc"),days);//接受性交流里表分
		String ECStandard  = toolsUtils(map.get("ECSocre"),map.get("bsidEc"),days);//表达性交流里表分
		String FMStandard  = toolsUtils(map.get("FMSocre"),map.get("bsidFm"),days);//精细运动里表分
		String GMStandard  = toolsUtils(map.get("GMSocre"),map.get("bsidGm"),days);//大运动里表分
		mapOut.put("cogStandard", cogStandard);
		mapOut.put("RCStandard", RCStandard);
		mapOut.put("ECStandard", ECStandard);
		mapOut.put("FMStandard", FMStandard);
		mapOut.put("GMStandard", GMStandard);

		int RCStandardInt = 0;
		int ECStandardInt = 0;
		int FMStandardInt = 0;
		int GMStandardInt = 0;
		int cogStandardInt = 0;

		int lang = 0;//语言总
		int mot = 0;// 运动总

		if(!StringUtils.isEmpty(RCStandard)) {
			RCStandardInt = Integer.parseInt(RCStandard);
		}
		if(!StringUtils.isEmpty(ECStandard)) {
			ECStandardInt = Integer.parseInt(ECStandard);
		}
		if(!StringUtils.isEmpty(FMStandard)) {
			FMStandardInt = Integer.parseInt(FMStandard);
		}
		if(!StringUtils.isEmpty(GMStandard)) {
			GMStandardInt = Integer.parseInt(GMStandard);
		}
		if(!StringUtils.isEmpty(cogStandard)) {
			cogStandardInt = Integer.parseInt(cogStandard);
		}

		lang = RCStandardInt+ECStandardInt;
		mot = FMStandardInt + GMStandardInt;
		mapOut.put("LangStandard", lang+"");
		mapOut.put("MotStandard", mot+"");

		net.sf.json.JSONObject json = null;//json串
		net.sf.json.JSONObject finalJson = net.sf.json.JSONObject.fromObject(map.get("bsidMix"));//入参json串
		net.sf.json.JSONArray finalArray = net.sf.json.JSONArray.fromObject(finalJson.get("LangOrMot"));//语言运动发育商
		net.sf.json.JSONArray finalArray1 = net.sf.json.JSONArray.fromObject(finalJson.get("cognize"));//认知商

		//特殊处理
		if(lang<2) {
			mapOut.put("LangDiscuss", "<46");
			mapOut.put("LangPersent", "<0.1");
		}
		if(mot<2) {
			mapOut.put("MotDiscuss", "<46");
			mapOut.put("MotPersent", "<0.1");
		}
		if(cogStandardInt<1) {
			mapOut.put("cogDiscuss", "<55");
			mapOut.put("cogPersent", "<0.1");
		}
		//匹配语言运动发育商
		for(int i =0;i<finalArray.size();i++) {
    		json = finalArray.getJSONObject(i);
    		if((lang+"").equals(json.get("value"))) {
    			mapOut.put("LangDiscuss", json.get("discuss"));
    			mapOut.put("LangPersent", json.get("persent"));
    		}
    		if((mot+"").equals(json.get("value"))) {
    			mapOut.put("MotDiscuss", json.get("discuss"));
    			mapOut.put("MotPersent", json.get("persent"));
    		}
    	}
		//认知商匹配
		for(int i =0;i<finalArray1.size();i++) {
    		json = finalArray1.getJSONObject(i);
    		if((cogStandardInt+"").equals(json.get("value"))) {
    			mapOut.put("cogDiscuss", json.get("discuss"));
    			mapOut.put("cogPersent", json.get("persent"));
    		}
    	}
		//发育龄匹配
		String cogAge  = matchAge(map.get("cogScore"),finalJson.get("age"),"cognize");//认知发育龄
		String RCSAge  = matchAge(map.get("RCSocre"),finalJson.get("age"),"accept");//接受性交流发育龄
		String ECAge  = matchAge(map.get("ECSocre"),finalJson.get("age"),"express");//表达性交流发育龄
		String FMAge  = matchAge(map.get("FMSocre"),finalJson.get("age"),"careful");//精细运动发育龄
		String GMAge  = matchAge(map.get("GMSocre"),finalJson.get("age"),"big");//大运动发育龄
		mapOut.put("cogAge", cogAge);
		mapOut.put("RCSAge", RCSAge);
		mapOut.put("ECAge", ECAge);
		mapOut.put("FMAge", FMAge);
		mapOut.put("GMAge", GMAge);
		return mapOut;
	}

	private String toolsUtils (Object score,Object jsons,int days) {
		String outStr ="";
		int scoreInt = 0;
    	String [] arg=  null;
		net.sf.json.JSONObject finalJson = null;//入参json串
		net.sf.json.JSONArray finalArray = null;//匹配上的json对象数组
		net.sf.json.JSONObject json = null;//json串
		if(!StringUtils.isEmpty(score)) {
			//认知分数匹配
			finalJson = net.sf.json.JSONObject.fromObject(jsons);
			Iterator<?> iterator = finalJson.keys();
            while(iterator.hasNext()){
                    String key = (String) iterator.next();
                    arg = key.split("-");
                    if(days>=Integer.parseInt(arg[0]) && Integer.parseInt(arg[1])>=days) {
                    	finalArray  = finalJson.getJSONArray(key);
                    }
            }
            if(finalArray!=null) {
            	for(int i =0;i<finalArray.size();i++) {
            		json = finalArray.getJSONObject(i);
            		if(json.get("basic").toString().indexOf("-")==-1) {
            			if(score.equals(json.get("basic"))) {
            				outStr = (String)json.get("value");
                		}
            		}else {
            			arg = json.get("basic").toString().split("-");
            			scoreInt = Integer.parseInt((String)score);
            			if(scoreInt>=Integer.parseInt(arg[0])&&Integer.parseInt(arg[1])>=scoreInt) {
            				outStr = (String)json.get("value");
                		}
            		}
            	}
            }
		}
		return outStr;
    }

	//匹配发育龄公共方法
	private String matchAge (Object score,Object jsons,String type) {
		String outStr ="";
    	String [] arg=  null;
    	int scoreInt = 0;
		net.sf.json.JSONArray finalArray = null;//匹配上的json对象数组
		net.sf.json.JSONObject json = null;//json串
		if(!StringUtils.isEmpty(score)) {
			//认知分数匹配
			finalArray = net.sf.json.JSONArray.fromObject(jsons);
            if(finalArray!=null) {
            	for(int i =0;i<finalArray.size();i++) {
            		json = finalArray.getJSONObject(i);
            		if(json.get(type).toString().indexOf("-")==-1) {
            			if((score+"").equals(json.get(type))) {
            				outStr = (String)json.get("developmentAge");
                		}
            		}else {

            			arg = json.get(type).toString().split("-");
            			scoreInt = Integer.parseInt((String)score);
            			if(scoreInt>=Integer.parseInt(arg[0])&&Integer.parseInt(arg[1])>=scoreInt) {
            				outStr = (String)json.get("developmentAge");
                		}
            		}
            	}
            }
		}
		return outStr;
    }

	@Override
	public Map<String, Object> getYYJLScore(Map<String, Object> map)throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
		String examinationPaperName = (String) map.get("evaluationType");
		JSONObject postionJson =null;
		try {
			String postionIds = (String)map.get("postionIds");
			postionJson = JSON.parseObject(postionIds);
		}catch(Exception e) {
			postionJson = ToolUtils.typeCast(map.get("postionIds"));
		}
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			int scoresTotal  = (int) postionJson.get("scoresTotal");//总分
			String json1= jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PHQGAD);
			if (StringUtils.isEmpty(json1)) {
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key", Constants.FOLLOW_EVALUATION_PREGNANT_PHQGAD);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if (null != position) {
					json1 = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PHQGAD, json1);
				}
			}
			JSONObject json = null;//是抑郁还是焦虑
			if(Constants.FOLLOW_EVALUATION_PREGNANT_SDS2.equals(examinationPaperName)) {
				json = JSON.parseObject(json1).getJSONObject(Constants.FOLLOW_EVALUATION_PREGNANT_SDS2);
			}else if(Constants.FOLLOW_EVALUATION_PREGNANT_SAS2.equals(examinationPaperName)) {
				json = JSON.parseObject(json1).getJSONObject(Constants.FOLLOW_EVALUATION_PREGNANT_SAS2);
			}
			String level = matchPHQ(scoresTotal,json);
			rspMap.put("scoresTotal", scoresTotal);
			rspMap.put("level", level);
			rspMap.put("lens", postionJson.get("lens"));
			} catch (JedisConnectionException jex) {
				logger.error("redis连接异常..." + jex.getMessage());
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
			} finally {
				if (null != jedis) {
					try {
						jedis.close();
						logger.warn("close redis connection...");
					} catch (Exception ex) {
						ex.printStackTrace();
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
								"Redis缓存关闭失败!"));
					}
				}
			}
		return rspMap;
	}

	private String matchPHQ (int score,Object jsons) {
    	String [] arg=  null;
		net.sf.json.JSONObject finalJson = null;//入参json串
		String level = "";
		if(!StringUtils.isEmpty(score)) {
		//认知分数匹配
		finalJson = net.sf.json.JSONObject.fromObject(jsons);
		Iterator<?> iterator = finalJson.keys();
        while(iterator.hasNext()){
            String key = (String) iterator.next();
            arg = key.split("-");
            if(score>=Integer.parseInt(arg[0]) && Integer.parseInt(arg[1])>=score) {
            	level  = finalJson.getString(key);
            }
          }
	   }
		return level;
	}

	//计算生活事件得分
	@Override
	public Map<String, Object> getLESScore(Map<String, Object> map)throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
		//String examinationPaperName = (String) map.get("evaluationType");
		//JSONObject postionJson =null;
		/*try {
			String postionIds = (String)map.get("postionIds");
			postionJson = JSON.parseObject(postionIds);
		}catch(Exception e) {
			postionJson = ToolUtils.typeCast(map.get("postionIds"));
		}*/
		String postionIds = map.get("postionIds").toString();
		@SuppressWarnings("unchecked")
		Map<String,Object> map6 = JSON.parseObject(postionIds,LinkedHashMap.class);
        int scoreMain = 0;
        int scoreLoss = 0;
        int scoreTitle = 0;
        int score3 = 0;
        int score4 = 0;
        int score5 = 0;
        for (String key : map6.keySet()) {
        	String value = map6.get(key).toString();
        	Map<String,Object> map7 = JSON.parseObject(value);
    		if("A".equals(map7.get("2"))) {
    			if("A".equals(map7.get("3"))) {
    				score3 = 0;
    			}else if("B".equals(map7.get("3"))) {
    				score3 = 1;
    			}else if("C".equals(map7.get("3"))) {
    				score3 = 2;
    			}else if("D".equals(map7.get("3"))) {
    				score3 = 3;
    			}else if("E".equals(map7.get("3"))) {
    				score3 = 4;
    			}
    			if("A".equals(map7.get("4"))) {
    				score4 = 1;
    			}else if("B".equals(map7.get("4"))) {
    				score4 = 2;
    			}else if("C".equals(map7.get("4"))) {
    				score4 = 3;
    			}else if("D".equals(map7.get("4"))) {
    				score4 = 4;
    			}
    			if(!StringUtils.isEmpty(map7.get("5"))) {
    				score5 = (int) map7.get("5");
    			}
    			scoreMain = scoreMain + score3*score4*score5;
        	}else {
        		if("A".equals(map7.get("3"))) {
    				score3 = 0;
    			}else if("B".equals(map7.get("3"))) {
    				score3 = 1;
    			}else if("C".equals(map7.get("3"))) {
    				score3 = 2;
    			}else if("D".equals(map7.get("3"))) {
    				score3 = 3;
    			}else if("E".equals(map7.get("3"))) {
    				score3 = 4;
    			}
    			if("A".equals(map7.get("4"))) {
    				score4 = 1;
    			}else if("B".equals(map7.get("4"))) {
    				score4 = 2;
    			}else if("C".equals(map7.get("4"))) {
    				score4 = 3;
    			}else if("D".equals(map7.get("4"))) {
    				score4 = 4;
    			}
    			if(!StringUtils.isEmpty(map7.get("5"))) {
    				score5 = (int) map7.get("5");
    			}
    			scoreLoss = scoreLoss + score3*score4*score5;
        	}

        }
        scoreTitle = scoreLoss + scoreMain;
        rspMap.put("scoreTitle", scoreTitle);
        rspMap.put("scoreLoss", scoreLoss);
        rspMap.put("scoreMain", scoreMain);
		return rspMap;
	}

	//计算中形式是这样的没有问题
	@Override
	public Map<String, Object> getOSIScore(Map<String, Object> map) throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
		JSONObject postionJson =null;
		try {
			String postionIds = (String)map.get("postionIds");
			postionJson = JSON.parseObject(postionIds);
		}catch(Exception e) {
			postionJson = ToolUtils.typeCast(map.get("postionIds"));
		}

		double IUT = MateOSI.getTaskRuleTime(postionJson, "IUT");
		double CUT = MateOSI.getTaskRuleTime(postionJson, "CUT");
		double OUT = MateOSI.getTaskRuleTime(postionJson, "OUT");
		double GUT = MateOSI.getTaskRuleTime(postionJson, "GUT");
		double total1 = IUT + CUT + OUT + GUT;
		rspMap.put("IUT", IUT);
		rspMap.put("CUT", CUT);
		rspMap.put("OUT", OUT);
		rspMap.put("GUT", GUT);
		rspMap.put("total1", total1);

		double IHT = MateOSI.getTaskRuleTime(postionJson, "IHT");
		double CHT = MateOSI.getTaskRuleTime(postionJson, "CHT");//存在问题后期需要修改
		double OHT = MateOSI.getTaskRuleTime(postionJson, "OHT");
		double GHT = MateOSI.getTaskRuleTime(postionJson, "GHT");
		double total2 = IHT + CHT + OHT + GHT;
		rspMap.put("IHT", IHT);
		rspMap.put("CHT", CHT);
		rspMap.put("CHT", CHT);
		rspMap.put("GHT", GHT);
		rspMap.put("total2", total2);

		double IST = MateOSI.getTaskRuleTime(postionJson, "IST");
		double CST = MateOSI.getTaskRuleTime(postionJson, "CST");
		double OST = MateOSI.getTaskRuleTime(postionJson, "OST");
		double GST = MateOSI.getTaskRuleTime(postionJson, "GST");
		double total3 = IST + CST + OST + GST;
		rspMap.put("IST", IST);
		rspMap.put("CST", CST);
		rspMap.put("OST", OST);
		rspMap.put("GST", GST);
		rspMap.put("total3", total3);

		double IEPT = MateOSI.getTaskRuleTime(postionJson, "IEPT");
		double CEPT = MateOSI.getTaskRuleTime(postionJson, "CEPT");
		double OEPT = MateOSI.getTaskRuleTime(postionJson, "OEPT");
		double GEPT = MateOSI.getTaskRuleTime(postionJson, "GEPT");
		double total4 = IEPT + CEPT + OEPT + GEPT;
		rspMap.put("IEPT", IEPT);
		rspMap.put("CEPT", CEPT);
		rspMap.put("OEPT", OEPT);
		rspMap.put("GEPT", GEPT);
		rspMap.put("total4", total4);

		double INOXT = MateOSI.getTaskRuleTime(postionJson, "INOXT");
		double ONOXT = MateOSI.getTaskRuleTime(postionJson, "ONOXT");
		double GNOXT = MateOSI.getTaskRuleTime(postionJson, "GNOXT");
		double total5 = INOXT + ONOXT + GNOXT;
		rspMap.put("INOXT", INOXT);
		rspMap.put("ONOXT", ONOXT);
		rspMap.put("GNOXT", GNOXT);
		rspMap.put("total5", total5);

		double IAVOIT = MateOSI.getTaskRuleTime(postionJson, "IAVOIT");
		double CAVOIT = MateOSI.getTaskRuleTime(postionJson, "CAVOIT");
		double OAVOIT = MateOSI.getTaskRuleTime(postionJson, "OAVOIT");
		double GAVOIT = MateOSI.getTaskRuleTime(postionJson, "GAVOIT");
		double total6 = IAVOIT + CAVOIT + OAVOIT + GAVOIT;
		rspMap.put("IAVOIT", IAVOIT);
		rspMap.put("CAVOIT", CAVOIT);
		rspMap.put("OAVOIT", OAVOIT);
		rspMap.put("GAVOIT", GAVOIT);
		rspMap.put("total6", total6);

		double ICNFLT = MateOSI.getTaskRuleTime(postionJson, "ICNFLT");
		double CCNFLT = MateOSI.getTaskRuleTime(postionJson, "CCNFLT");
		double OCNFLT = MateOSI.getTaskRuleTime(postionJson, "OCNFLT");
		double GCNFLT = MateOSI.getTaskRuleTime(postionJson, "GCNFLT");
		double total7 = ICNFLT + CCNFLT + OCNFLT + GCNFLT;
		rspMap.put("ICNFLT", ICNFLT);
		rspMap.put("CCNFLT", CCNFLT);
		rspMap.put("OCNFLT", OCNFLT);
		rspMap.put("GCNFLT", GCNFLT);
		rspMap.put("total7", total7);

		double total = total1 + total2+ total3+total4+total5+total6+total7;
		rspMap.put("total", total);

		return rspMap;
	}


	//计算高危儿五项
	@Override
	public Map<String, Object> getFHRISScore(Map<String, Object> map)throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
		JSONArray postionJson =null;
		try {
			String postionScores = (String)map.get("postionScores");
			postionJson = JSONArray.parseArray(postionScores);
		}catch(Exception e) {
			postionJson = ToolUtils.typeCast(map.get("postionScores"));
		}
		List<Map<String,Object>> list =  new ArrayList<Map<String,Object>>();
		//解析将不正常的数据返回
       for(int i=0;i<postionJson.size();i++) {
    	   JSONObject json = postionJson.getJSONObject(i);
     	   if((int)json.get("id")!=8) {
     		  List<Map<String,Object>> lists =  ToolUtils.typeCast(json.get("answer"));
     		  String colour = (String) lists.get(0).get("colour");
 			 if(!colour.equals("green")) {
     			 list.add(json);
     		  }
     	   }else {
     		  list.add(json);
     	   }
       }
       	rspMap.put("score", list);
		return rspMap;
	}

	@Override
	public Map<String, Object> getDSTScore(Map<String, Object> mapIn) throws Exception {
		JSONObject jsonEsb = null;
		try {
			String postions = (String) mapIn.get("postionIds");
			jsonEsb = JSON.parseObject(postions);
		} catch (Exception e) {
			jsonEsb = (JSONObject) mapIn.get("postionIds");
		}
		// 传入答题 结果
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 小写的mm表示的是分钟
		boolean flag = false;// 是否早产.默认非早产儿
		Patient patient = (Patient) mapIn.get("patient");
		String birthday = patient.getBirthday();
		if (null == birthday) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_BIRTHDAY_NOT_EXIST, "用户没有出生日期");
		}
		Date date = new Date();
		String createTime = sdf.format(date);// 评估时间
		String expectedDay = patient.getExpectedDay();
		// 预产期，是否有预产期，如果没有默认是非早产儿
		// 如果有预产期，判断是否早产
		int mouth = 0;// 月数
		int day = 0;// 天数
		if (null != expectedDay) {
			// 比较两个时间的大小
			int bigOne = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
			Date date1 = sdf.parse(expectedDay);
			Date date2 = sdf.parse(birthday);
			Date date3 = sdf.parse(createTime);// 评估时间
			// 计算两个时间差(评估时用户年龄)
			int ages = DateUtil.daysBetween(date2, date3);
			int ageMouth = ages / 30;

			// 如果预产期大于出生日期 孕周小于37周，显示为早产,并计算出时间差
			if (bigOne < 260 && ageMouth < 25) {
				int expect = DateUtil.daysBetween(date2, date1);
				flag = true;
				mouth = expect / 30;
				day = expect % 30;
			}
		}
		// 计算月龄
		int day3 = 0;// 天
		int month3 = 0;// 月
		int year3 = 0;// 年
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("birthday", birthday);
		map.put("createTime", createTime);
		// 调用计算组件
		Map<String, Object> mapOut = ToolUtils.CalculateAgeOfMoon(map);
		if (mapOut != null && mapOut.size() > 0) {
			day3 = (int) mapOut.get("day3");
			month3 = (int) mapOut.get("month3");
			year3 = (int) mapOut.get("year3");
		}
		// 如果是早产儿，且年龄在24个月之内的儿童需要计算纠正年龄 flag=true 为早产儿
		// 用计算出来的月龄减去早产的时间获取纠正年龄
		if (flag) {
			if (day3 > day || day3 == day) {
				day3 = day3 - day;
			} else {
				if (month3 > mouth) {
					day3 = day3 + 30 - day;
					month3 = month3 - 1;
				} else {
					if (year3 > 0) {
						day3 = day3 + 30 - day;
						month3 = month3 + 12 - 1;
						year3 = year3 - 1;
					}
				}
			}
			if (month3 > mouth) {
				month3 = month3 - mouth;
			} else {
				if (year3 > 0) {
					month3 = month3 + 12 - mouth;
					year3 = year3 - 1;
				}
			}
		}
		// 计算最后的月龄
		int days = year3 * 365 + month3 * 30 + day3;
		DecimalFormat df = new DecimalFormat("0.0");//格式化小数
	    String moonStr = df.format((float)days/30);//返回的是String类型
		double moon = Double.parseDouble(moonStr);
		//判断年龄是否在2~30月之间
		map.clear();// 清空信息
		map.put("moon", moon);
		map.put("days", days);
		map.put("Result", jsonEsb.toJSONString());
		Map<String, Object> MapOut = new HashMap<String,Object>();
		MapOut = getDSTAnswer(map,patient);
		return MapOut;
	}

	//DST
	private Map<String, Object> getDSTAnswer(Map<String, Object> map,Patient pt) throws Exception{
		logger.info(" getDSTAnswer :    "+map.toString());
		Map<String, Object> mapOutstr = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			//月龄
			double moon  = (double) map.get("moon");
			net.sf.json.JSONObject json = null;
			try {
				String postions = (String) map.get("Result");
				json = net.sf.json.JSONObject.fromObject(postions);
			} catch (Exception e) {
				json = (net.sf.json.JSONObject) map.get("Result");
			}
			//判断是否有值
			if(json!=null) {
				/**原始分获取*/
				//运动
				net.sf.json.JSONObject sports = json.getJSONObject("sports");
				//社会
				net.sf.json.JSONObject sociology = json.getJSONObject("sociology");
				//智力
				net.sf.json.JSONObject intelligence = json.getJSONObject("intelligence");
				int sportsScore = 0;
				int sociologyScore= 0;
				int intelligenceScore = 0;
				//计算得分
				String key= "";
				if(sports!=null&&sports.size()>0) {
			        Iterator<?> iterator = sports.keys();
			        while(iterator.hasNext()){
			                key = (String) iterator.next();
			                if(sports.get(key)!=null) {
			                	sportsScore = sportsScore+ (int)sports.get(key);
			                }
			        }
				}
				if(sociology!=null&&sociology.size()>0) {
			        Iterator<?> iterator = sociology.keys();
			        while(iterator.hasNext()){
			                key = (String) iterator.next();
			                if(sociology.get(key)!=null) {
			                	sociologyScore = sociologyScore+ (int)sociology.get(key);
			                }
			        }
				}
				if(intelligence!=null&&intelligence.size()>0) {
			        Iterator<?> iterator = intelligence.keys();
			        while(iterator.hasNext()){
			                key = (String) iterator.next();
			                if(intelligence.get(key)!=null) {
			                	intelligenceScore = intelligenceScore+ (int)intelligence.get(key);
			                }
			        }
				}
				/**评分表获取*/
				String json1 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,
						Constants.FOLLOW_EVALUATION_DSTANSWER);

				//如果在redis中无法查询到，则通过数据库查询，然后放入redis缓存中
				if (StringUtils.isEmpty(json1)) {
					paramMap.put("field", Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
					paramMap.put("key", Constants.FOLLOW_EVALUATION_DSTANSWER);
					FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
					if(null != position){
						json1 = position.getValue();
						jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_DSTANSWER,json1);
					}
				}

				int total = sportsScore+sociologyScore+intelligenceScore;
				logger.info("total: "+total  + " sportsScore : "+sportsScore +" sociologyScore:"+sociologyScore + " intelligenceScore:"+intelligenceScore);
				String DQ  = toolsDST(total,json1,moon,"DQ");
				String MI  = toolsDST(intelligenceScore,json1,moon,"MI");
				mapOutstr.put("DQ",DQ);
				mapOutstr.put("MI",MI);
				mapOutstr.put("sportsScore",sportsScore);
				mapOutstr.put("sociologyScore",sociologyScore);
				mapOutstr.put("intelligenceScore",intelligenceScore);
				logger.info("mapOutstr : "+mapOutstr.toString());
			}

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
							"Redis缓存关闭失败!"));
				}
			}
		}
		return mapOutstr;
	}


	private String toolsDST (int score,Object jsons,double month,String type) {
		String outStr ="";
		//需要处理去尾
		int monthInt = (int)month;
		net.sf.json.JSONObject finalJson = null;//入参json串
		net.sf.json.JSONArray finalArray = null;//匹配上的json对象数组
		net.sf.json.JSONObject json = null;//json串
		String [] arg =null;
		if(!StringUtils.isEmpty(score)) {
			String keys = "";
			//认知分数匹配
			finalJson = net.sf.json.JSONObject.fromObject(jsons).getJSONObject(type);
			Iterator<?> iterator = finalJson.keys();
            while(iterator.hasNext()){
                    String key = (String) iterator.next();
                    if(key.indexOf("-")==-1) {
            			if(monthInt==Integer.parseInt(key)) {
            				finalArray  = finalJson.getJSONArray(key);
                		}
            		}else {
            			arg = key.split("-");
            			if(monthInt>=Integer.parseInt(arg[0]) && Integer.parseInt(arg[1])>=monthInt) {
                        	finalArray  = finalJson.getJSONArray(key);
                        }
            		}

            }
            if(finalArray!=null) {
            	for(int i =0;i<finalArray.size();i++) {
            		json = finalArray.getJSONObject(i);
            		if(i==0) {
            			Iterator<?> iterator1 = json.keys();
                        while(iterator1.hasNext()){
                        		keys = (String) iterator1.next();
                           }
            		}
            		if(StringUtils.isEmpty(json.get(""+score))) {
            			continue;
            		}else {
            			outStr= (String) json.get(""+score);
            			break;
            		}
            	}
            //判断是否存在当前数据
        	if(!StringUtils.isEmpty(keys) && StringUtils.isEmpty(outStr)) {
        			if(score<Integer.parseInt(keys)) {
        				outStr = "低于50";
        			}else {
        				outStr = "高于150";
        			}
            	}
            }
		}
		return outStr;
    }


    	//gesell匹配发育等级
	public String matchlevel(float DQ) {
		String level="";
		if(DQ>75) {
			level = "发育正常";
		}else if(DQ<=75&&DQ>=55) {
			level = "轻度落后";
		}else if(DQ<=54&&DQ>=40) {
			level = "中度落后";
		}else if(DQ<=39&&DQ>=25) {
			level = "重度落后";
		}else if(DQ<25) {
			level = "极重度落后";
		}
		return level;
	}

	/**
	 * 同步(抑郁/焦虑)问卷数据到医院
	 * 判断是否预约--->是否绑卡(绑卡)-->判断是否做过答卷-->同步数据
	 * @throws Exception
	 */
	public boolean synchroToEsb(HashMap<String,Object> paramMap) throws Exception{
		Patient pt = (Patient)paramMap.get("patient");
		Map<String,Object> patientMap = Collections.synchronizedMap(new HashMap<String,Object>());
		patientMap.put("id", pt.getId());
		logger.info("进入通过患者id查询用户绑定卡信息");
		List<Map<String, Object>> patientlist = patientqueryCardDAO.selectcardId(patientMap);//查询绑卡信息
		String pathash = "";
		if(CollectionUtils.isEmpty(patientlist)){
			logger.info("用户绑定卡信息不存在");
			return false;
		}else{
			pathash = (String)patientlist.get(0).get("pathash");
		}
		if(StringUtils.isEmpty(pathash)){
			HashMap<String,Object> servParamMap = new HashMap<String,Object>();
			servParamMap.put("code", Constants.STRING_SERVICECODE_A09U003O);
			servParamMap.put("patName", pt.getUserName());
			servParamMap.put("pattel", pt.getPhoneNo());
			servParamMap.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
			servParamMap.put("platform_key", pt.getId());
			servParamMap.put("pathash", "");
			servParamMap.put("bookeddept", "002");
			servParamMap.put("is_bind", "no");
			servParamMap.put("cardno", "");
			logger.info("建卡查询参数(抑郁/焦虑param):--------" + servParamMap.toString());
			//
			//验证用户是否在医院预约
			String cardmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", servParamMap);
			List<Map<String, Object>> listcard = ToolUtils.FormatXml(cardmsg);
			logger.info("验证预约-返回：" + listcard.toString());
			if (listcard != null && listcard.size() > 0 && !StringUtils.isEmpty(listcard.get(0).get("cardno"))) {
				String cardno = listcard.get(0).get("cardno").toString();
				pathash = listcard.get(0).get("pathash").toString();
				if(StringUtils.isEmpty(pathash)){//判断是否绑卡,未建卡则先绑卡后获取pathash
					servParamMap.put("is_bind", "bind");
					servParamMap.put("cardno", cardno);
					servParamMap.put("code", Constants.STRING_SERVICECODE_A09U003O);
					//绑卡
					String pathashmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", servParamMap);
					List<Map<String, Object>> pathashlist = ToolUtils.FormatXml(pathashmsg);
					logger.info("绑卡-返回：" + pathashlist.toString());
					if(pathashlist != null && pathashlist.size() > 0 && !StringUtils.isEmpty(pathashlist.get(0).get("pathash"))){
						pathash = pathashlist.get(0).get("pathash").toString();
						// 绑卡时更新当前用户卡信息pt_queuescheme_info
						String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
						String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
						servParamMap.put("cardno", cardno);
						servParamMap.put("pathash", pathash);
						servParamMap.put("updateTime", updateTime);
						servParamMap.put("cardName", Constants.GFY_ZHUSU_CARDNAME);
						servParamMap.put("updateAccept", updateAccept);
						servParamMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
						servParamMap.put("queueId", paramMap.get("queueId"));
						// 先入历史
						patientqueryCardDAO.PatientQueueSchemeHis(servParamMap);
						patientqueryCardDAO.updateCardThings(servParamMap);
					}else{
						logger.info("用户绑卡失败");
						return false;
					}
				}
			}else{
				logger.info("数据同步失败,用户未预约");
				return false;
			}
		}
		//获取量表答卷状态
		Map<String,Object> anserStatusParamMap = Collections.synchronizedMap(new HashMap<String,Object>());
		anserStatusParamMap.put("code", Constants.STRING_SERVICECODE_A09U008O);
		anserStatusParamMap.put("patName", pt.getUserName());
		anserStatusParamMap.put("pathash",pathash);//识别码
		anserStatusParamMap.put("platform_code",Constants.SOURCE_HOSPTAL_CODE);
		anserStatusParamMap.put("platform_key",pt.getId());
		//判断焦虑还是抑郁
		String examinationPaperName = (String)paramMap.get("evaluationType");
		if(Constants.FOLLOW_EVALUATION_PREGNANT_SDS2.equals(examinationPaperName)) {//抑郁
			anserStatusParamMap.put("lbtype",Constants.CONTTEMPL_PHQ9);
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_SAS2.equals(examinationPaperName)) {//焦虑
			anserStatusParamMap.put("lbtype",Constants.CONTTEMPL_GAD7);
		}
		logger.info("答卷状态参数(抑郁/焦虑param):--------" + anserStatusParamMap.toString());
		//答卷对应的预约id
		String bookid = "";
		String anserStatus = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", anserStatusParamMap);
		List<Map<String, Object>> listanserStatus = ToolUtils.FormatXml(anserStatus);
		logger.info("验证答卷状态-返回：" + listanserStatus.toString());
		if (listanserStatus != null && listanserStatus.size() > 0 && !StringUtils.isEmpty(listanserStatus.get(0).get("bookid")) && !StringUtils.isEmpty(listanserStatus.get(0).get("is_reg"))) {
			String isreg = listanserStatus.get(0).get("is_reg").toString();//获取答卷状态
			bookid = listanserStatus.get(0).get("bookid").toString();
			if(!isreg.equals("0")){//答卷状态,0未做,1已做
				logger.info("量表答卷已存在");
				return false;
			}
		}else{
			logger.info("数据同步失败,预约id不存在");
			return false;
		}
		/***同步数据***/
		//参数
		anserStatusParamMap.put("bookid",bookid);//答卷对应的预约id
		anserStatusParamMap.put("code", Constants.STRING_SERVICECODE_A09U009O);
		JSONObject requestParam = (JSONObject) paramMap.get("postionIds");//问卷参数结果
		anserStatusParamMap.put("score",requestParam.get("scoresTotal"));//成绩
		JSONObject scoreParam = requestParam.getJSONObject("map");
		//各个文件的答案
		anserStatusParamMap.put("question1", scoreParam.get("1"));
		anserStatusParamMap.put("question2", scoreParam.get("2"));
		anserStatusParamMap.put("question3", scoreParam.get("3"));
		anserStatusParamMap.put("question4", scoreParam.get("4"));
		anserStatusParamMap.put("question5", scoreParam.get("5"));
		anserStatusParamMap.put("question6", scoreParam.get("6"));
		anserStatusParamMap.put("question7", scoreParam.get("7"));
		//判断焦虑还是抑郁
		if(Constants.FOLLOW_EVALUATION_PREGNANT_SDS2.equals(examinationPaperName)) {//抑郁
			anserStatusParamMap.put("question8", scoreParam.get("8"));
			anserStatusParamMap.put("question9", scoreParam.get("9"));
			anserStatusParamMap.put("influence", scoreParam.get("10"));
		}else if(Constants.FOLLOW_EVALUATION_PREGNANT_SAS2.equals(examinationPaperName)) {//焦虑
			anserStatusParamMap.put("influence", scoreParam.get("8"));
		}
		logger.info("数据同步查询参数(抑郁/焦虑param):--------" + anserStatusParamMap.toString());
		String resultId = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", anserStatusParamMap);
		List<Map<String, Object>> resultIdList = ToolUtils.FormatXml(resultId);
		logger.info("同步数据-返回：" + resultIdList.toString());
		logger.info("resultIdList:出参：" + resultIdList.toString());
		if (resultIdList == null || resultIdList.size() <= 0 || StringUtils.isEmpty(resultIdList.get(0).get("id"))) {
			logger.info("数据同步失败,同步返回id不存在");
			return false;
		}
		return true;
	}

	@Override
	public Map<String, Object> getNbnaGuide(Map<String, Object> map)throws Exception {
		Map<String,Object> rspMap = null;
		FuAssessMentPosition fuAssessMentPosition = followEvaluationDao.selectAssessMentPosition(map);
		if (fuAssessMentPosition != null) {
			rspMap = new HashMap<String,Object>();
			rspMap.put("age", fuAssessMentPosition.getKey());
			rspMap.put("guide", fuAssessMentPosition.getValue());
		}
		return rspMap;
	}


}


